Create a default nginx site rule

Create a default nginx site rule

Tags :

Category : How-to

Get Social!

nginx-logoUsually a web server can be accessed by multiple paths, such as the DNS entry of the server (eg. as www.jamescoyle.net) and the IP address of the server (eg. 10.10.10.1). This is a problem when it comes to presenting a single entry point to your website.

If you use Nginx to serve your website you can add a ‘catch-all’ entry to respond to requiests which do not match an IP based or server_name attribute.

Let’s say you had an Nginx sites-enabled site which responded to www.jamescoyle.net specified by the server_name attribute.

server {
        listen       80;
        server_name  www.jamescoyle.net;
        location / {
                ...

Without a catch all entry, all requests to the server would be served as if they were requesting www.jamescoyle.net when in fact they could be using the web server IP address. Ideally, we want to handle all requests coming to www.jamescoyle.net and redirect any other requests to www.jamescoyle.net. The default_server statement in the listen command specifies that this server code block will respond if no other code blocks do. In the above example, that code block will handle all reuests to www.jamescoyle.net and all other requests will be issued a redirect.

The following code will redirect all unanswered requests to http://www.jamescoyle.net.

server {
    listen 80 default_server;
    return 301 http://www.jamescoyle.net;
}

Visit our advertisers

Quick Poll

What type of VPN protocol do you use?

Visit our advertisers