【问题标题】:Updating Nginx block to do two things that aren't working更新 Nginx 块来做两件不起作用的事情
【发布时间】:2021-08-20 12:39:59
【问题描述】:

对于 Nginx,我正在尝试做两件事:

  1. 将访问该站点的任何人从 www 重定向到非 www。
  2. 当 URL 路径不存在时,服务器默认为错误 500 而不是 404。

这是我当前的服务器配置:

server {
        root /var/www/project/;
        index index.php index.html index.htm index.nginx-debian.html;
        server_name example.com www.example.com;

        location / {
                 try_files $uri $uri/ /index.php$is_args$args;
        }

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

        location ~ /\.ht {
                deny all;
        }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed$
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # manag$
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot


}

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


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


        listen 80;
        server_name example.com www.example.com;
    return 404; # managed by Certbot
}

我尝试为任何 www 流量添加转发以进入非 www,但这没有做任何事情(我认为是因为 certbot)。此外,我尝试更新返回 404 而不是 500 的 URL,但它所做的是它使主页之外的任何内容成为 404。所以我将其重置为您在上面看到的内容。

【问题讨论】:

    标签: nginx server


    【解决方案1】:
    1. 将访问该站点的任何人从 www 重定向到非 www。

    最干净的解决方案是仅为此目的定义一个单独的server 块:

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

    您可以通过输入验证它是否有效

    127.0.0.1 localhost example.com www.example.com
    

    在您计算机的主机文件中。

    $ curl -I http://www.example.com
    HTTP/1.1 301 Moved Permanently
    Server: nginx
    Date: Fri, 27 Aug 2021 06:14:43 GMT
    Content-Type: text/html
    Content-Length: 162
    Connection: keep-alive
    Location: http://example.com/
    
    1. 当 URL 路径不存在时,服务器默认为错误 500 而不是 404。

    500 HTTP 状态码可能是由您的index.php 脚本引起的。

    【讨论】:

    • 这不会将用户从 www 重新路由到非 www
    • 它应该可以工作,我实际测试过它(请参阅我编辑的答案)。如果它不适合您,那么您很可能还有其他问题。另请注意,如果同时使用 HTTP 和 HTTPS,则必须配置两个块。
    猜你喜欢
    • 2019-03-07
    • 2015-01-18
    • 2016-01-22
    • 1970-01-01
    • 2021-10-13
    • 2022-09-23
    • 2017-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多