简体   繁体   中英

How to Redirect a non-www to www with Mutiple Sites? (Nginx and Varnish)

First I want to clarify that I searched a lot about this issue, but I haven't found a solution.

I have 2 Wordpress sites configured under the same Nginx (port 8080) and Varnish (port 80).

This is my actual setting:

map $http_host $blogid {
 default 0;
 www.site1.com 1;
 www.site2.com 2;
}
server {
 listen 8080;
 server_name www.site1.com site1.com;
 root /var/www/site1.com;
 ...
}
server {
 listen 8080;
 server_name www.site2.com site2.com;
 root /var/www/site2.com;
 ...
}

What I want to do, is to configure a redirect for site2 from a non-www to a www. Example: http://site2.com -> http://www.site2.com

I added another ' server ' configuration with the redirect, and let just ' www.site2.com ' in the other ' server_name '.

map $http_host $blogid {
 default 0;
 www.site1.com 1;
 www.site2.com 2;
}
server {
 server_name www.site1.com site1.com;
 root /var/www/site1.com;
 ...
}
server {
    listen 8080;
    server_name site2.com;
    return 301 http://www.site2.com$request_uri;
}
server {
 server_name www.site2.com;
 root /var/www/site2.com;
 ...
}

After changed with the configuration above and restarting Nginx, what happened is when accessing " http://site2.com " (without www) it is loading the content from " http://site1.com " (url continues site2.com without www). Acessing " http://www.site2.com " shows the right content.

What I'm doing wrong?

I think that redirect is not working because I tried to redirect to Google.com, but it didn't redirect. It keeps loading "site1.com" content inside "site2.com".

return 301 http://www.google.com

I tried this code below, but with the same result:

rewrite ^(.*) http://www.site2.com$1 permanent;

My complete Nginx configuration : http://codepad.org/TfPHS0jH

Your site isn't being served by Nginx but by Varnish.

When you navigate to any of http://www.siteX.com or http://siteX.com , you are going to http://www.siteX.com:80 or http://siteX.com:80 and according to your explanation, Varnish listens on Port 80, not Nginx.

There is no real reason to ever have to use the two together (despite what you may have read on some websites) and you should get rid or one or the other and focus on the one you decide to keep.

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