【问题标题】:Nginx redirect www domain to non-wwwNginx 将 www 域重定向到非 www
【发布时间】:2020-12-31 23:47:47
【问题描述】:

我希望 www.example.app 去 example.app 进行 SEO,我遵循了几个教程和问题解决方案,但似乎无法让它发挥作用。

我添加了一个单独的服务器块,该块重定向到非 www 域并多次重新启动 nginx,还从隐身窗口访问我的网站。

这是我的 /etc/nginx/sites-available/default 配置文件。

任何帮助将不胜感激!

server {
    server_name www.example.app;
    return 301 $scheme://example.app$request_uri;
}

server {
    listen 80;
    listen [::]:80;


    root /var/www/html/;

    index index.php index.html index.htm index.nginx-debian.html;

    server_name exampe.app;

    location / {
        try_files $uri $uri/ =404;
    }
    
    location ~*  \.(jpg|jpeg|png|gif|ico|css|js)$ {
            expires 365d;
        }

        location ~*  \.(pdf)$ {
            expires 30d;
        }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    }

    location ~ /\.ht {
     deny all;
    }

    error_page 404 /customerror_404.html;
    location = /customerror_404.html {
        root /usr/shar/nginx/html;
        internal;
    }
    
}


server {
    root /var/www/html/;
    index index.php index.html index.htm index.nginx-debian.html;
    server_name example.app; # managed by Certbot


    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    }

    location ~ /\.ht {
        deny all;
    }


    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.app/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.app/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}


server {
    if ($host = example.app) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80 ;
    listen [::]:80 ;
    server_name example.app;
    return 404; # managed by Certbot

}

【问题讨论】:

    标签: ubuntu nginx redirect certbot


    【解决方案1】:
    server {
        if ($host = www.example.app) {
            return 301 https://$host$request_uri;
        } # managed by Certbot
    
    
        listen 80 ;
        listen [::]:80 ;
        server_name example.app;
        return 404; # managed by Certbot
    
    }
    

    我使用它从 www 域重定向到非 www 域。

    你需要告诉 nginx 在这种情况下你想从哪个主机重定向来自 www。

    如果这不起作用。您可能需要将服务器名称设置为这样

    server_name www.example.app example.app;
    

    所以主机被识别出来了。

    【讨论】:

    • 通过在末尾添加您的代码块进行了尝试。我还将server_name 更改为您的建议,但没有运气。还是不行。
    • 只是出于好奇。您的服务器上的 80 端口是否开放?
    • 是的,端口是开放的。
    • 我将尝试复制您的场景并回复您。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 2017-06-20
    • 2017-03-10
    相关资源
    最近更新 更多