Nginx Cheat Sheet

Last Updated on


Test and restart an nginx configuration change

The reload will not happen if the test fails.

sudo nginx -t && service nginx reload

or, on a bitnami image:

sudo nginx -t && sudo /opt/bitnami/ctlscript.sh restart nginx

 


Redirect all subdomains to the top level domain

ie: http://www.mydomain.com -> http://mydomain.com

In your DNS management system, you’ll want to create a wildcard CNAME record:
Host: “*” Value: “mydomain.com”

Then, on your server that runs nginx you’ll want to create two server blocks as shown below.
These can be for your main host or in a virtual host.

server {
        listen 80;
        listen [::]:80;
        root /var/www/mydomain.com;
        index index.html;
        server_name mydomain.com;
        location / {
                try_files $uri $uri/ =404;
        }
}

server {
        listen 80;
        listen [::]:80;
        server_name *.mydomain.com;
        return 301 http://mydomain.com$request_uri;
}

 


Rewrite/Redirect old URLs to a new URL with a 301/Permanent status
server {
        listen 80;
        listen [::]:80;
        root /var/www/myolddomain.com;
        index index.html;
        server_name myolddomain.com;
        location / {
                try_files $uri $uri/ =404;
        }
        rewrite ^/my/old/url/$ https://mynewdomain.com/the/new/url/ permanent;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.