Nginx rewrite everything in index.php except whitelist

First of all, I tried to find similar questions, but the solutions to these questions were specific lines of code that I could not configure to fit my needs.

I have a Codeigniter installation and I'm trying to upgrade from Apache to nginx. However, Apache.htaccess was pretty simple: it would take a whitelist and copy everything else to index.php.

RewriteEngine on
RewriteCond $1 !^(index\.php|css|images|core|uploads|js|robots\.txt|favicon\.ico)
RewriteRule ^(.*)$ /index.php/$1 [L]

However, in nginx I tried the if and try_files directives, and also messed around with locations, but to no avail. I'm still not familiar with the way nginx reads the server configuration, and the tutorials on the Internet are somewhat confused.

Additionally , index.php will not be located in the root directory of the website, but in a subdirectory server.

Because of this, I also need to make sure that even URI requests starting with / server do not go to the directory, but to index.php

This is my nginx virtual host configuration:

server {
    listen 80;
    server_name example.com;

    root /home/example/public_html;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;


    location / {
        index index.htm index.html index.php;
    }

    location ~ \.php$ {
        fastcgi_pass        unix:/var/run/php-fpm/example.sock;
        include             fastcgi_params;
        fastcgi_param       PATH_INFO $fastcgi_script_name;
        fastcgi_param       SCRIPT_FILENAME $document_root$fastcgi_script_name;

    }

    location ~* ^.*(/|\..*) { 
        try_files $uri $uri/ /server/index.php;
    }

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

This helps redirect requests to index.php, but does not have a whitelist. I would appreciate it if someone could create a working example with a brief explanation of what each part does.

+5
source share
1 answer

I would use the $ uri and if variable in a block locationto achieve this.

location / {
    if ( $uri !~ ^/(index\.php|css|images|core|uploads|js|robots\.txt|favicon\.ico) ) {
        rewrite ^ /server/index.php last;
    }
}

In addition, regarding pathinfo security issues , ( discussion ), it is recommended to add

try_files $uri =403;
fastcgi_split_path_info ^(.+.php)(.*)$;

into the block location ~ \.php$.

+12
source

All Articles