I’ve recently begun working with Nginx as we’re finally moving off of Apache in our infrastructure. The first thing I noticed is documentation for various types of configurations is a bit sporadic. A lot is outdated and many don’t use best practices.
The first application I’m working on is a CodeIgniter-based PHP site which needs a few rewrite rules to function properly. I dug up this tutorial but it unfortunately uses a lot of if statements which I quickly learned are evil in Nginx.
Below is the configuration that I’ve settled upon (for now) which takes into account some best practices including:
- uses php-fpm for the upstream server via a unix socket
- redirects all http://www.example.com traffic to example.com
- passes all requests under the root to the front-controller as long as they don’t exist (allows nginx to directly serve static files)
- prevents uncontrolled requests from being passed to php
- prevents any access to leftover .htaccess files
I’m hoping to add some of the additional rewrite functionality found in the tutorial at a later date.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
upstream php { | |
server unix:/var/run/php5-fpm.sock; | |
} | |
server { | |
# enforce NO www | |
server_name http://www.example.com; | |
return 301 $scheme://example.com$request_uri; | |
} | |
server { | |
listen 80; | |
server_name example.com; | |
root /home/webapps/www.example.com/; | |
access_log /var/log/nginx/www.example.com.access.log main; | |
location / { | |
index index.php; | |
# pass requests to the front controller (http://wiki.nginx.org/Pitfalls#Front_Controller_Pattern_based_packages) | |
# but don't proxy everything (http://wiki.nginx.org/Pitfalls#Proxy_Everything) | |
try_files $uri $uri/ /index.php; | |
} | |
location ~ \.php$ { | |
# dont pass uncontrolled requests to php (http://wiki.nginx.org/Pitfalls#Passing_Uncontrolled_Requests_to_PHP) | |
try_files $uri =404; | |
fastcgi_pass php; | |
fastcgi_index index.php; | |
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; | |
include /etc/nginx/fastcgi_params; | |
} | |
# deny access to .htaccess files | |
location ~ /\.ht { | |
deny all; | |
} | |
} |