Buzut
Buzut

Reputation: 5153

Nginx doesn't redirect if url has .html extension

I'm trying to serve a maintenance page. So I gave try_files a try and always serve maintenance.html.

It works well if url is like app.amazing.com or anything like app.amazing.com/[a-z0-9]* but as soon as there's a html extension, Nginx tries to serve this very file (exemple : app.amazing.com/test.html) and returns a 404 if it doesn't exist.

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;
    }
}

I also tried a rewrite like that:

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

I even tried this if-based solution, but nothing seems to work. Did I miss something?

Upvotes: 0

Views: 1038

Answers (1)

Bogdan Anghel
Bogdan Anghel

Reputation: 184

UPDATE: tested and working

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;
    }

}

Please change the 404 code to 503, like this:

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 = NOT FOUND

UPDATE: 302 = TEMPORARY REDIRECT

Upvotes: 1

Related Questions