Return custom 403 error page with nginx

前端 未结 4 2028
星月不相逢
星月不相逢 2021-01-04 19:27

Im trying to display the error page in /temp/www/error403.html whenever a 403 error occurs.

This should be whenever a user tries to access the site via https (ssl) a

4条回答
  •  囚心锁ツ
    2021-01-04 20:01

    I had the same issue... The point is that i've implemented ip whitelist at server context level (or vhost level if you prefer), so every locations will have this as well (basicaly /403.html won't be accessible) :

    server {
      listen       *:443 ssl;
      server_name  mydomain.com ;
      error_page 403 /403.html;
      .....
      if ($exclusion = 0) { return 403; } #implemented in another conf.d files (see below)
      location ~ \.php$ {
        root          /var/www/vhosts/mydomain.com/httpdocs;
        include       /etc/nginx/fastcgi_par
        fastcgi_pass  127.0.0.1:9000;
        fastcgi_connect_timeout 3m;
        fastcgi_read_timeout 3m;
        fastcgi_send_timeout 3m;
      }
      location /403.html {
        root      /usr/share/nginx/html;
        allow all;
      }
    
      ...
    }
    

    Exclusion conf.d file sample:

    geo $exclusion {
      default 0;
      10.0.0.0/8  Local network
      80.23.120.23 Some_ip
      ...
    }
    

    To fix that simply do your return 403 at location level (context):

    server {
      listen       *:443 ssl;
      server_name  mydomain.com ;
      error_page 403 /403.html;
      .....
      location ~ \.php$ {
        if ($exclusion = 0) { return 403; } 
        root          /var/www/vhosts/mydomain.com/httpdocs;
        include       /etc/nginx/fastcgi_par
        fastcgi_pass  127.0.0.1:9000;
        fastcgi_connect_timeout 3m;
        fastcgi_read_timeout 3m;
        fastcgi_send_timeout 3m;
      }
      location /403.html {
        root      /usr/share/nginx/html;
        allow all;
      }
    
      ...
    }
    

    Works for me.

提交回复
热议问题