Example 301 redirection configuration for domain name and directory in nginx
- 2020-05-12 06:28:58
- OfStack
301 redirection is not unknown, sometimes there is a need to redirect a directory to 1 level 2 domain name, or not with www top-level domain request all redirection to www level 2 domain name. If it is Apache, need to configure.htaccess, nginx does not support, need to use rewrite command in the configuration file to achieve.
Top-level domain redirects to www
server {
server_name ofstack.com;
rewrite ^/(.*)$ //www.ofstack.com/$1 permanent;
}
ofstack.com requests are redirected to www.ofstack.com,301 redirects are helpful for SEO. This configuration is most commonly used.
The www2 level domain is redirected to the top-level domain
server {
server_name www.ofstack.com;
rewrite ^/(.*)$ http://domain.com/$1 permanent;
}
Some seoer requests that operations 1 transfer www's request to the 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 plans to create a domain name.
Attachment: 301 jumps between domains and test methods
1. Jump between the same root domain and subdomain
Case 1: access to the root domain is redirected to the www subdomain (Vhost is usually bound to multiple domain names, so that it can be accurately located to a domain name without causing the non-domain name to jump to this domain name)
server {
server_name www.ofstack.com ofstack.com;
if ($host = 'ofstack.com' ) {
rewrite ^/(.*)$ //www.ofstack.com/$1 permanent;
}
2. 301 jumps between different domains
Case 1: visit A station and direct to B station
server {
server_name www.ofstack.com;
rewrite ^(.*) //www.ofstack.com$1 permanent;
}
Case 2: not all redirects to the specified page for access to the A site
server {
server_name www.ofstack.com;
if ($host != 'ofstack.com') {
rewrite ^/(.*)$ //www.ofstack.com/$1 permanent;
}
}
If I write it in the first server
Access using IP will also be redirected
301 redirection 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