如果url具有.html扩展名,则Nginx不会重定向

时间:2017-06-30 10:32:33

标签: redirect nginx

我试图提供维护页面。所以我尝试了try_files并始终提供maintenance.html

如果网址类似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,但似乎没有任何效果。我错过了什么吗?

1 个答案:

答案 0 :(得分: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 = TEMPORARY REDIRECT