Nginx Cheatsheet

Blog by Daniel Hauck. Sysadmin, Developer, Blogger.

Nginx Cheatsheet

From day to day I need some nginx snippets and they are often the same. I bet some other people are in the same situation and may this page will be handy for you. If you got something to add, please comment, so everybody can profit from it. Thanks!

Redirect all traffic to ssl

It just redirects any traffic to https and tells search engines to always look for https because of the 301 return code.

Substitute from url

If you are switching from a static site blog to a cms and want to redirect old routes, this may be useful for you.

Simple 301 redirect with exact location

Redirect /foo to /bar with 301.

Rewrite Part at the beginning of the URL

Rewrite all traffic going to /category/ to /cat/. For example /category/great-post will become /cat/great-post. There will be times, when you change the URL layout of you website. You need to redirect all old links, so to not make users and search engines freak out.

Rewrite other parts of the URL

Let’s say you changed the url for user accounts from /tom/profile/ to /tom/account/. Tom has saved this URL as a bookmark. You don’t want Tom to get angry! Help him and just replace the part of the url.

Deliver file on location

In some cases you just want to deliver a single file from somewhere else then your web root. In my case it’s often the robots.txt. This snippet will help you:

Deliver directory on location

Same as above and as simple as above.

PHP-FPM proxy pass + try files

We all need to run php through nginx from time to time. If you got an app that runs on index.php, here’s how to do it: