首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Nginx将www和非www请求转发到一个目录?

Nginx将www和非www请求转发到一个目录?
EN

Stack Overflow用户
提问于 2011-08-18 11:10:00
回答 3查看 1.1K关注 0票数 2

我有一个MediaTemple服务器,我从它为许多网站提供服务。我使用nginx,并有以下配置文件。我正确地将所有非www流量(即http://example.com)转发到适当的目录。但是,所有www流量都返回404,因为我的配置文件查找的是/directory-structure/www.sitename.com而不是/directory-structure/sitename.com

如何将www和非www请求都放到一个目录中?谢谢。

代码语言:javascript
复制
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; }
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-08-19 16:15:01

从0.7.40版本开始,Nginx接受server_name中的正则表达式并捕获。因此,可以提取域名(没有www)并在root指令中使用此变量:

代码语言:javascript
复制
server_name ~^(?:www\.)?(.+)$ ;
root /var/www/vhosts/$1/httpdocs;

从0.8.25开始,可以使用命名捕获:

代码语言:javascript
复制
server_name ~^(?:www\.)?(?P<domain>.+)$ ;
root /var/www/vhosts/$domain/httpdocs;

另一种定义命名捕获的语法是(?<domain>.+) (PCRE7.0及更高版本)。有关PCRE版本here的更多信息

票数 3
EN

Stack Overflow用户

发布于 2011-08-19 11:59:52

尝试此操作,并在上面的服务器配置中添加以下内容:

代码语言:javascript
复制
if ($host = "www.example.com") {
    rewrite  (.*)  http://example.org$1;
}

这里发生了什么,我们指示nginx将页面作为http://example.com提供服务,即使浏览器的网址是http://www.example.com -我希望这能起作用。

更新

对于通用版本,请尝试以下操作:

代码语言:javascript
复制
if ($host ~* "www.(.*)") {
    rewrite  ^  http://$1$request_uri?;
}
票数 1
EN

Stack Overflow用户

发布于 2012-05-10 01:38:20

考虑到在RakeshS的答案评论中链接到的if的潜在问题,以及RakashS的答案无论如何都不适用于我的事实,这里有一个解决方案应该更安全,并且适用于我的Nginx 1.0.14。

为执行重写的每个服务器部分添加一个额外的服务器条目:

代码语言:javascript
复制
server {
    server_name www.yourwebsite.com;
    rewrite ^ $scheme://yourwebsite.com$request_uri permanent;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7101952

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档