June 8, 2012 - Warren Held

Nginx: Add WWW To A Domain With Rewrite Rule And Redirect

I just recently switched this website from running on the Apache web server to Nginx (Engine X). I noticed that for whatever reason the Advanced Slider gallery that I had purchased was stuck in some weird Error 404 loop when trying to load the gallery. Using Firebug I was able to see that it kept on requesting two images, the server would return a 404, and then it would request them again. When I manually browsed to the images using warrenheld.com I got a Error 404.  When I tried browsing to them using www.warrenheld.com it worked just fine.  I’m not sure if this is an issue with Advanced Slider + Nginx, or just an Nginx problem.  I figured the easiest way to make it work was to just redirect to www.warrenheld.com when the server receives a request without the www.  We need to open up the nginx.conf file (usually located in /etc/nginx/) and set up our server block to accept connections on www.yourdomain.tld and then create a “catch all” server block that will receive any requests that any of your other server blocks do no accept, and then rewrite the request with the www attached. This is what I used for my “catch all” block. Notice there is a space between server_name and the following _;

##### Default "Catch All" #####
server {
listen 80 default_server;
server_name _; #invalid value which will never trigger on a real hostname
rewrite ^ $scheme://www.$host$request_uri;

This is what I used for my domain server block:

##### WarrenHeld.com #####
server {
server_name www.warrenheld.com;


Nginx nginx /