我有一个MediaTemple服务器,我从它为许多网站提供服务。我使用nginx,并有以下配置文件。我正确地将所有非www流量(即http://example.com)转发到适当的目录。但是,所有www流量都返回404,因为我的配置文件查找的是/directory-structure/www.sitename.com而不是/directory-structure/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; }
}发布于 2011-08-19 16:15:01
从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>.+) (PCRE7.0及更高版本)。有关PCRE版本here的更多信息
发布于 2011-08-19 11:59:52
尝试此操作,并在上面的服务器配置中添加以下内容:
if ($host = "www.example.com") {
rewrite (.*) http://example.org$1;
}这里发生了什么,我们指示nginx将页面作为http://example.com提供服务,即使浏览器的网址是http://www.example.com -我希望这能起作用。
更新
对于通用版本,请尝试以下操作:
if ($host ~* "www.(.*)") {
rewrite ^ http://$1$request_uri?;
}发布于 2012-05-10 01:38:20
考虑到在RakeshS的答案评论中链接到的if的潜在问题,以及RakashS的答案无论如何都不适用于我的事实,这里有一个解决方案应该更安全,并且适用于我的Nginx 1.0.14。
为执行重写的每个服务器部分添加一个额外的服务器条目:
server {
server_name www.yourwebsite.com;
rewrite ^ $scheme://yourwebsite.com$request_uri permanent;
}https://stackoverflow.com/questions/7101952
复制相似问题