Nginx将www和非www请求转发到一个目录? [英] Nginx forward www and non-www requests to one directory?

查看:337
本文介绍了Nginx将www和非www请求转发到一个目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如何将www和非www请求都转到一个目录?谢谢.

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; }
}

推荐答案

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

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;

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

Starting with 0.8.25 it is possible to use named captures:

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

定义命名捕获的另一种语法是(?<domain>.+)(PCRE版本7.0及更高版本).有关PCRE版本的更多信息,请此处

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

这篇关于Nginx将www和非www请求转发到一个目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆