Example of 301 redirection configuration for domain names and directories in nginx
- 2020-05-07 20:55:26
- OfStack
301 redirection is not unknown, sometimes there is a need to redirect the entire directory to 1 2-level domain, or the top-level domain without www requests all redirection to the 2-level domain with www.
The top-level domain is redirected to www
server {
server_name ofstack.com;
rewrite ^/(.*)$ //www.ofstack.com/$1 permanent;
}
The above configuration so that requests for ofstack.com will be redirected to www.ofstack.com,301 is helpful for SEO.
www2-level domain redirects to the top-level domain
server {
server_name www.ofstack.com;
rewrite ^/(.*)$ http://domain.com/$1 permanent;
}
Some seoer will require operations 1 to transfer www's request to a top-level domain, as opposed to the above.
directory redirection
if ( $request_filename ~ nginxjiaocheng/ ) {
rewrite ^ //www.ofstack.com/nginx/? permanent;
}
directory jumps to new domain name
if ( $request_filename ~ nginx/ ) {
rewrite ^ http://nginx.ofstack.com/? permanent;
}
nginx is so popular that it's going to have a domain name.
attachment: 301 jumps between domains and test method
1. Jump between the same root domain and subdomain
Case 1: access to the root domain redirect to the www subdomain (Vhost is usually bound to more than one domain name, this can accurately locate a domain name, will not cause the non-domain to jump to this domain)
server {
server_name www.ofstack.com ofstack.com;
if ($host = 'ofstack.com' ) {
rewrite ^/(.*)$ //www.ofstack.com/$1 permanent;
}
2. 301 jump between different domains
Case 1: visit A station and be directed to B station
server {
server_name www.ofstack.com;
rewrite ^(.*) //www.ofstack.com$1 permanent;
}
Case 2: not all redirects to the specified page that access the A station
server {
server_name www.ofstack.com;
if ($host != 'ofstack.com') {
rewrite ^/(.*)$ //www.ofstack.com/$1 permanent;
}
}
If it's in the first server paragraph
Access using IP will also be redirected
301 redirect status online detection tool: http:// web-sniffer.net /
A 301 redirect is successful when this sentence is returned:
Status: HTTP/1.1 301 Moved Permanently