简体   繁体   中英

How to redirect a specific path to the same path without www in nginx

I've encountered an issue during server configuration: I require a 301 redirect from http://www.example.com to http://example.com just for one specific url alias - like /partners.

the expected output- http:// www.example.com/partners/stuff -> http:// example.com/partners/stuff.

I've tried adding the following code to the vhosts already:

server { 
        server_name http://www.example.com/partners; 
        return 301 $scheme://example.com/partners;
}

but vhosts gives me an error telling me this code isn't valid.
What's the correct way of implementing such rewrite?

server_name is for domain only. I can suggest you 2 solutions.

Copy configs between servers. This is the best solution recommended by nginx's author.

server {
   server_name example.com;
   include example.com.conf;
}

server {
   server_name www.example.com;
   include example.com.conf;
   location /partners/ {
      return 301 $scheme://example.com$request_uri;
   }
}

Or using if. Bad solution due performance

server {
   server_name .example.com;
   ...
   location /partners/ {
      if ($host = "www.example.com") {
         return 301 $scheme://example.com$request_uri;
      }
   }
}

http://wiki.nginx.org/IfIsEvil

http://wiki.nginx.org/Pitfalls#Server_Name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM