我有一个 MediaTemple 服务器,我通过它为许多网站提供服务。我使用 nginx 并有以下配置文件。我正确地将所有非 www 流量(即 http://example.com )转发到适当的目录。但是,所有 www 流量都返回 404,因为我的配置文件正在寻找/directory-struct/www.sitename.com 而不是/directory-struct/sitename.com
如何让 www 和非 www 请求都发送到一个目录?谢谢。
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; }
}
最佳答案
从 0.7.40 版本开始,Nginx 接受 server_name
中的正则表达式并捕获。因此,可以提取域名(不带 www
)并在 root
中使用此变量。指令:
server_name ~^(?:www\.)?(.+)$ ;
root /var/www/vhosts/$1/httpdocs;
从 0.8.25 开始,可以使用命名捕获:
server_name ~^(?:www\.)?(?P<domain>.+)$ ;
root /var/www/vhosts/$domain/httpdocs;
定义命名捕获的另一种语法是 (?<domain>.+)
(PCRE 版本 7.0 及更高版本)。有关 PCRE 版本的更多信息 here
关于Nginx 将 www 和非 www 请求转发到一个目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7101952/