no-www for nginx

If you happen to be in no-www camp and want to redirect people accessing www.whateverdomain.com to the no-www version but have lots of domain, instead of writing one by one and you’re not keen in using config generator (I’m not), you can use this:

server {
  listen 80;
  listen [::]:80 ipv6only=on;
  server_name ~^www.(?<domain>.+)$;
  rewrite ^ $scheme://$domain$request_uri? permanent;
  access_log /var/log/nginx/access-no_www.log;
}

Remove listen [::]:80 ipv6only=on; if you’re not using IPv6 and adjust the log file path to wherever you want (or just turn off or remove it altogether).

Note that this trick doesn’t work well with HTTPS/SSL domains since you’ll get big fat warning about incorrect domain name in certificate or about self-signed certificate if you’re using wildcard one.

Forcing SSL with nginx and Apache

Not really difficult but I guess it would be useful for some people.

First one is for nginx: create a file called `force-ssl.conf` and put in nginx’s config directory (check by `nginx -V`). And its content is:

if ($scheme = http) {
rewrite ^ https://$host$request_uri? permanent;
}

Include this file (by `include force-ssl.conf;`) in any `location … { }` block you want to force SSL on.

As for Apache, we can do it by using the usual `.htaccess` (and put in corresponding directories):

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI}

The nginx rule is written by me, Apache rule is written by [someone on internet](http://joseph.randomnetworks.com/2004/07/22/redirect-to-ssl-using-apaches-htaccess/) with minor fix on skipping regex capture (`(.*)` replaced by `^`).

nginx/php 404 proper handler

If you find “No file specified” error message disturbing (as I did), here’s the configuration to remove it!

location ~ .php$ {
try_files $uri =404;
include /etc/nginx/fastcgi_params;
fastcgi_pass 127.0.0.1:55555;
fastcgi_index index.php;
fastcgi_param  SCRIPT_FILENAME    $request_filename;
}

Don’t use `if (-f $request_filename)` – it won’t work and if is evil. Also the `try_files` will ensure that the file actually exists – effectively disabling possible vulnerability with public file upload on certain conditions.

_Last update 2011-07-10 20:16: working version, markdown-fied_

nginx links

Here are the links I find useful:

* [Why nginx](http://hostingfu.com/article/nginx-vs-lighttpd-for-a-small-vps)
* [WordPress with nginx](http://elasticdog.com/2008/02/howto-install-wordpress-on-nginx/)

Note that the latter link should not be followed anymore.

_Last update 2011-07-10 20:24: markdown-fied_