如何阻止 nginx 添加结尾斜杠

如何阻止 nginx 添加结尾斜杠

我不知道为什么,但是如果我去example.com/aboutnginx 会返回 301 并直接转到example.com/about/(带有尾部斜杠)。

这是我的配置。它基本上只是默认的 ubuntu apt-get 配置:

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}


http {
    server {
        root /var/www/html/my-site/public_html/;

        location / {}

        listen 443 ssl; # managed by Certbot
        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    }


    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;


    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    gzip on;


    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

在导航到目录并加载其 index.html 文件时,如何防止此设置添加尾随斜杠?


日志

301 网络事件

-- General --
Request URL: https://example.com/about
Request Method: GET
Status Code: 301 Moved Permanently
Remote Address: 11.222.33.444:555
Referrer Policy: no-referrer-when-downgrade

-- Response Headers --
HTTP/1.1 301 Moved Permanently
Server: nginx/1.14.0 (Ubuntu)
Date: Tue, 10 Dec 2019 19:42:32 GMT
Content-Type: text/html
Content-Length: 194
Location: https://example.com/about/
Connection: keep-alive

200 网络事件

-- General --
Request URL: https://example.com/about/
Request Method: GET
Status Code: 200 OK
Remote Address: 11.222.33.444:555
Referrer Policy: no-referrer-when-downgrade

nginx 日志

11.222.333.44 - - [10/Dec/2019:19:42:32 +0000] "GET /about HTTP/1.1" 301 194 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36"

11.222.333.44 - - [10/Dec/2019:19:42:33 +0000] "GET /about/ HTTP/1.1" 200 3482 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36"

答案1

大多数服务器的默认行为是在目录对应的 URL 后面添加一个斜杠。如果要禁用此行为,请修改您的location定义:

location / {
    try_files $uri $uri/index.html =404;
}

如果您想要反转约定并将带有斜杠的目录重定向到不带斜杠的形式,请使用:

location / {
    rewrite ^/index.html$ / permanent;
    rewrite ^(.+)/$ $1 permanent;
    rewrite ^(.+)/index.html$ $1 permanent;
    try_files $uri $uri/index.html =404;
}

这样,您还可以隐藏索引文件的名称。

相关内容