【问题标题】:Nginx doesn't redirect if url has .html extension如果 url 具有 .html 扩展名,Nginx 不会重定向
【发布时间】:2017-06-30 10:32:32
【问题描述】:

我正在尝试提供维护页面。所以我尝试了try_files 并始终为maintenance.html 服务。

如果 url 类似于 app.amazing.com 或类似 app.amazing.com/[a-z0-9]* 的任何内容,它运行良好,但只要有 html 扩展名,Nginx 就会尝试提供这个文件(例如:app.amazing.com/test.html)并返回 404 如果它不存在。

server {
    listen [::]:443;
    listen 443;

    server_name app.amazing.com;
    root /var/www/front/public;
    include /etc/nginx/conf.d/expires.conf;

    charset utf-8;

    location / {
        try_files /maintenance.html =404;
    }
}

我也尝试过这样的重写:

location / {
        rewrite (.*) /maintenance.html break;
}

我什至尝试过这个if-based solution,但似乎没有任何效果。我错过了什么吗?

【问题讨论】:

    标签: redirect nginx


    【解决方案1】:

    更新:经过测试并正常工作

    server {
        listen [::]:443;
        listen 443;
    
        server_name app.amazing.com;
        root /var/www/front/public;
        include /etc/nginx/conf.d/expires.conf;
    
        charset utf-8;
    
        set $maintenance on;
        if ($uri ~* \.(ico|css|js|gif|jpe?g|png|html)(\?[0-9]+)? ) {
            set $maintenance off;
        }
        if ($maintenance = on) {
            return 503;
        }
        error_page 503 @maintenance;
        location @maintenance {
            rewrite ^(.*)$ /maintenance.html break;
        }   
        location / {
            # here hoes your usual location / rules
            try_files $uri $uri/ =404;
        }
    
    }
    

    请将 404 代码更改为 503,如下所示:

    server {
        listen [::]:443;
        listen 443;
    
        server_name app.amazing.com;
        root /var/www/front/public;
        include /etc/nginx/conf.d/expires.conf;
    
        charset utf-8;
    
        location / {
            try_files $uri $uri/ =404;
        }
    }
    

    404 = 未找到

    更新: 302 = 临时重定向

    【讨论】:

    • 503 不是重定向。应该使用 3XX。
    • 我认为=404 是为了以防maintenance.html 不存在。但是对于重定向,它更准确。无论如何,这并没有改变输入app.amazing.com/test.html 仍然返回 404 的事实。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 2014-11-23
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    相关资源
    最近更新 更多