Nginx deny IP’s and setting custom 403 downloads a file

denyhttp-status-code-403nginxUbuntu

I've attached my Nginx conf file for my default site which runs on Ubuntu.

What I'm trying to achieve is the following:

  1. Main directory is /usr/share/nginx/www with the default file index.php
  2. Restricting IP addresses for now until launch so only my IP's can view the site
  3. For everyone else that attempts to visit the site, deny them, but display a custom 403 page which is 403.html which is sitting in the /usr/share/nginx/www main directory

What happens though is when I visit the site from a different IP address (one that is denied access) it will load the 403.html page but download a file called "download". If I visit example.com/index.php it will download an index.php file.

Something isn't configured correctly but unsure what it is.

server {
        listen   80;


        root /usr/share/nginx/www;
        index index.php;

        server_name example.com;

        location / {
                try_files $uri $uri/ /index.php;

                # restrict IP's
                allow 123.456.789.0;
                allow 123.456.789.1;
                deny all;
        }

        location = /403.html {
           root   /usr/share/nginx/www;
           allow all;
        }

        error_page 404 /404.html;
        error_page 403 /403.html;       

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
              root /usr/share/nginx/www;
             # root /var/www;
        }

        # pass the PHP scripts to FastCGI server listening on the php-fpm socket
        location ~ \.php$ {
                try_files $uri =404;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;

        }

}

Best Answer

You should move your deny rules from location / one level up, because now they are not applied to php requests.

server {
        listen   80;


        root /usr/share/nginx/www;
        index index.php;

        server_name example.com;

        allow 123.456.789.0;
        allow 123.456.789.1;
        deny all;

        location / {
                try_files $uri $uri/ /index.php;
        }

        #....

        # pass the PHP scripts to FastCGI server listening on the php-fpm socket
        location ~ \.php$ {
                try_files $uri =404;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
}