将 Nginx 的非 www 转到 www,并将 www 转到非 www。

发布时间 2023-11-20 18:56:57作者: 小满独家

内容来自 DOC https://q.houxu6.top/?s=将 Nginx 的非 www 转到 www,并将 www 转到非 www。

我正在按照教程在 Rackspace 云上使用 Nginx(参考链接:http://www.howtoforge.com/running-phpmyadmin-on-nginx-lemp-on-debian-squeeze-ubuntu-11.04),在网上搜索了一番,但迄今为止未能解决这个问题。

我希望 www.mysite.example 可以正常地重定向到 mysite.example,以满足 SEO 等需求。

我的 /etc/nginx/sites-available/www.example.com.vhost 配置文件如下:

server {
       listen 80;
       server_name www.example.com example.com;
       root /var/www/www.example.com/web;

       if ($http_host != "www.example.com") {
                 rewrite ^ http://example.com$request_uri permanent;
       }

我还尝试过以下配置:

server {
       listen 80;
       server_name example.com;
       root /var/www/www.example.com/web;

       if ($http_host != "www.example.com") {
                 rewrite ^ http://example.com$request_uri permanent;
       }

我还尝试过以下配置。然而,这两次尝试都导致了重定向循环错误:

if ($host = 'www.example.com' ) {
rewrite ^ http://example.com$uri permanent;
}

我的 DNS 设置是标准的:

site.example 192.192.6.8 A 类型每 300 秒刷新一次
www.site.example 192.192.6.8 A 类型每 300 秒刷新一次

(示例中的 IP 地址和文件夹仅供说明和帮助未来的用户参考)。我使用的是 Ubuntu 11。


HTTP 解决方案

根据文档的说明,"正确的方式是为 example.org 定义一个单独的服务器":

server {
    listen       80;
    server_name  example.com;
    return       301 http://www.example.com$request_uri;
}

server {
    listen       80;
    server_name  www.example.com;
    ...
}

HTTPS 解决方案

对于那些希望包含 https:// 的解决方案...

server {
        listen 80;
        server_name www.domain.example;
        # $scheme 表示获取 http 协议
        # 301 是平板电脑、手机、台式机和 SEO 的最佳实践
        return 301 $scheme://domain.example$request_uri;
}

server {
        listen 80;
        server_name domain.example;
        # 在此处放置其余配置文件
        # 示例
        location / {

            rewrite ^/cp/login?$ /cp/login.php last;
            # 等等...

        }
}

注意:我在解决方案中没有包含 https://,因为我们使用负载均衡器和高流量的 SSL 支付服务器:我们不混合使用 https://http://


要检查 Nginx 的版本,请使用 nginx -v 命令。

使用 Nginx 重定向删除 URL 中的 www

server {
    server_name  www.domain.example;
    rewrite ^(.*) http://domain.example$1 permanent;
}

server {
    server_name  domain.example;
    # 这里放置其余的配置#
}

所以你需要有两个服务器代码。

使用 Nginx 重定向在 URL 中添加 www

如果你需要相反的效果,从 domain.example 重定向到 www.domain.example,可以使用以下代码:

server {
    server_name  domain.example;
    rewrite ^(.*) http://www.domain.example$1 permanent;
}

server {
    server_name  www.domain.example;
    # 这里放置其余的配置#
}

可以想象,这只是相反的操作,与第一个示例的工作方式相同。这样,你不会降低 SEO 分数,因为它是完整的永久重定向和移动。没有 WWW 前缀被强制,目录会显示!

以下是一些我代码的示例:

server {
    server_name  www.google.com;
    rewrite ^(.*) http://google.com$1 permanent;
}
server {
       listen 80;
       server_name google.com;
       index index.php index.html;
       ####
       # 现在从一个目录中提取网站 #
       root /var/www/www.google.com/web;
       # 完成 #
       location = /favicon.ico {
                log_not_found off;
                access_log off;
       }
}