Nginx forward www and non-www requests to one dire

2019-05-22 15:19发布

问题:

I have a MediaTemple server from which I serve many websites. I use nginx and have the follow config file. I am correctly forwarding all non-www traffic (ie, http://example.com) to the appropriate directory. However, all the www traffic is returning 404 because my config file is looking for /directory-structure/www.sitename.com instead of /directory-structure/sitename.com

How can I have both www and non-www requests go to one directory? Thanks.

server {
listen 80;
server_name _;   
root /var/www/vhosts/$host/httpdocs/;
error_page 404 /;
location / {
    try_files $uri $uri/ /index.php;
}
location ~ \.php$ {
    try_files $uri =404;
    include fastcgi_params;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_script_name;
    #fastcgi_pass php;
    fastcgi_pass 127.0.0.1:9000;
}
location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
    expires max;
    add_header Pragma public;
    add_header Cache-Control "public, must-revalidate, proxy-revalidate";
}
# this prevents hidden files (beginning with a period) from being served
location ~ /\. { access_log off; log_not_found off; deny all; }
}

回答1:

Starting with version 0.7.40 Nginx accepts regular expressions in server_name and captures. Thus it's possible to extract a domain name (without www) and use this variable in root directive:

server_name ~^(?:www\.)?(.+)$ ;
root /var/www/vhosts/$1/httpdocs;

Starting with 0.8.25 it is possible to use named captures:

server_name ~^(?:www\.)?(?P<domain>.+)$ ;
root /var/www/vhosts/$domain/httpdocs;

Another syntax to define named captures is (?<domain>.+) (PCRE version 7.0 and later). More on PCRE versions here



回答2:

Try this and add the following in the above server config:

if ($host = "www.example.com") {
    rewrite  (.*)  http://example.org$1;
}

What happens here, we are instructin nginx to serve the pages as http://example.com even though the browser URL reads http://www.example.com - I hope this works.

UPDATE

Try this for a generic version:

if ($host ~* "www.(.*)") {
    rewrite  ^  http://$1$request_uri?;
}


回答3:

Given the potential issues with if as linked to in RakeshS's answer's comments, as well as the fact that RakashS's answer didn't work for me anyway, here's a solution that should be safer and worked for me with Nginx 1.0.14.

Add an additional server entry for each one of your server sections that does a rewrite:

server {
    server_name www.yourwebsite.com;
    rewrite ^ $scheme://yourwebsite.com$request_uri permanent;
}


标签: nginx