🌐 Path-Based Routing in Nginx
To serve different applications based on URL paths, configure Nginx with location
blocks. Below is an example configuration:
server {
listen 80;
server_name asifahmadkhan.com;
root /var/www/html/test/public;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location /routes {
alias /var/www/html/routetest/public/;
index index.html;
}
# to see laravel logs on the browser
location /logs {
default_type text/plain;
alias /var/www/html/screening-round/backend/storage/logs/laravel.log;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
📌 Explanation
🔹 Root Configuration:
server_name asifahmadkhan.com;
→ This specifies the domain name.root /var/www/html/test/public;
→ Sets the root directory for the default site.index index.php index.html;
→ Defines the default files to be served.
🔹 Handling Different Paths:
- 🏠
https://asifahmadkhan.com/
→ Serves content from/var/www/html/test/public
. - 📁
https://asifahmadkhan.com/routes
→ Serves content from/var/www/html/routetest/public/
. - 🔄
try_files $uri $uri/ /index.php?$query_string;
→ Ensures clean URL handling.
🔹 PHP Processing:
- 🖥️ Uses
fastcgi_pass
to route PHP files tophp8.2-fpm.sock
. - Sets
SCRIPT_FILENAME
to execute PHP scripts correctly.
🎯 Key Takeaways
✅ Path-based Routing allows serving multiple apps under different paths.
✅ Easy to extend by adding more location
blocks.
✅ Works with PHP applications using fastcgi_pass
.
✅ Can be combined with subdomain-based routing for better organization.
🚀 Now, you can efficiently host multiple apps on a single server using Nginx! 🎉