Nginx Location Configuration for Subfolders
In this article, we'll explore how to configure Nginx to serve content from two subfolders, one at the root path and the other at a specific URL.
Consider the following directory structure:
/var/www/myside/ ├── static ├── manage
Our goal is to make the /static folder accessible at the root URL (e.g., http://example.org/) and the /manage folder accessible at /manage (e.g., http://example.org/manage). In this case, the /manage folder contains Slim's PHP framework code, with the actual PHP file located in /var/www/mysite/manage/public/index.php.
Nginx Configuration
To achieve this, we can use Nginx's location directive. Here's a possible configuration:
server { listen 80; server_name example.org; error_log /usr/local/etc/nginx/logs/mysite/error.log; access_log /usr/local/etc/nginx/logs/mysite/access.log; root /var/www/mysite; location / { root /var/www/mysite/static; index index.html; } location /manage { alias /var/www/mysite/manage/public; index index.php; if (!-e $request_filename) { rewrite ^ /manage/index.php last; } location ~ \.php$ { if (!-f $request_filename) { return 404; } fastcgi_pass 127.0.0.1:9000; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $request_filename; fastcgi_param SCRIPT_NAME $fastcgi_script_name; } } location ~ \.php$ { try_files $uri =404; fastcgi_pass 127.0.0.1:9000; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_index index.php; } }
Explanation
Let's break down the configuration:
Usage of alias vs. root
When using alias, Nginx serves files from the specified directory while maintaining the original URI. This is useful for our purpose, as we want the /manage URI to point to the /var/www/mysite/manage/public directory.
In contrast, root changes the root directory for the location block, so it isn't suitable for our scenario where we want to serve different subfolders from different locations.
Rewrite Rule for index.php
The rewrite rule ensures that requests for non-existent files within the /manage folder are redirected to index.php. This allows Slim's PHP application to handle the request.
PHP File Handling
Both location blocks for PHP file handling include the necessary configuration for running PHP scripts, such as FastCGI settings and variables. The fastcgi_pass directive directs PHP requests to a PHP FastCGI server.
Final Notes
Be sure to ensure that your PHP FastCGI server is running and properly configured. This setup should allow you to serve content from both /static and /manage subfolders correctly.
The above is the detailed content of How to Configure Nginx to Serve Content from Two Subfolders with Different Root Paths?. For more information, please follow other related articles on the PHP Chinese website!