John Davidson

Nginx redirect all traffic to index.php, but don't allow arbitrary file access

0 comments
Message:


I have a legacy PHP app (Zend Framework) that I'm moving from Apache to Nginx. Except for things like web files (JS, CSS, images, fonts, etc.), all traffic needs to go through the index.php file in the root of the project folder. So I need to redirect all traffic to index.php, except for web files.


There are a lot of solutions to this that use try_files as a catch-all. Basically if a file is not found on the filesystem, nginx will send the request to index.php.


The problem with this is that the app stores its configuration file in a web-accessible path (i.e. in a subdirectory of the folder that holds index.php). So you could point your browser to the configuration file path and read it (e.g. https://example.com/config/app.xml). Since the file exists on the filesystem, nginx will serve it. There are actually a few more project config files that can be accessed in this way too.


So, how do I send all requests to index.php, except for web files, and also not allow arbitrary files to be read from the web?


Yes, I know I could update the app to access the config files in another location, but it's legacy and not super crucial. I don't want to spend more time on it than I have to and I don't want to break it.


I could also forbid access to any extensions that happen to be config files (e.g. xml, yml, etc.), but it's a big project and I don't want to risk missing something.


I figured out a solution. I didn't find anything that worked exactly the way I wanted online, so I'm asking this question in order to answer it.



My Answer:
To redirect all traffic to index.php in Nginx, you can use the following configuration in your Nginx server block:

nginx
server {
listen 80;
server_name example.com;

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

location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
}


In this configuration, the `location /` block will try to serve the requested URI directly, and if it doesn't exist, it will redirect to index.php with any query parameters passed along. The `location ~ \.php$` block is used to handle PHP files and pass them to the PHP-FPM process for execution.

Make sure to adjust the PHP-FPM socket path and server_name to match your setup. Additionally, you may need to include other configuration directives depending on your specific requirements.

Rate this post

3 of 5 based on 1985 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us