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

标签 nginx

我有一个 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/

相关文章:

php - IIS 到 nginx 迁移 : `unexpected " {"` erron on\d{^anum^, ^anum^} 条目到映射文件

nginx - 不用sudo重启nginx?

nginx 服务器对不同的子文件夹使用多个 fastcgi 后端

django - 用于开发和生产的 Dockerfile 的单独进程?

nginx - 部分加载的 javascript 文件

python - 解决 Gunicorn 下 Flask 的 TemplateNotFound 错误

nginx - 段错误(核心转储)

使用自动索引时 Nginx 错误 404

linux - 将 "handmade"htaccess 移至 nginx 配置

azure - 在 Azure Kubernetes 服务 (AKS) 中,我有一个类型为 "ClusterIP"的服务,它是否在内部执行 Pod 的负载平衡?