NginX with Web2py: Forcing a url to use a single domain

I have for some time wanted to find a simple way to force a domain into a single address www.domain or http://domain with web2py using routes.py and nginx. I did a bit of research more than a few times into routes.py and the mapping system seemed a bit confusing and time consuming for me to take my existing routed domains and make the necessary changes. So I began to look at the server configuration and here is what I came up with after a bit of research.

In your sites configuration file located at /etc/nginx/sites-available/web2py add (as an example) these additional values below the initial server entry.

server {
    server_name  domain1.com;
    rewrite ^(.*) $scheme://www.domain1.com$1 permanent;
}
server {
    server_name  domain2.com;
    rewrite ^(.*) $scheme://www.domain2.com$1 permanent;
}

Now in the initial server entry below, which should be added by default if you used the web2py setup script for nginx or you have done your own set up. Append these domain entries to the server_name

server {
        listen          80;
        server_name     $hostname www.domain1.com www.domain2.com subdomain.domain2.com;
	}

        location / {
        	uwsgi_pass      unix:///tmp/web2py.socket;
		uwsgi_read_timeout 300;
        	uwsgi_send_timeout 300;
		include         uwsgi_params;
        	uwsgi_param     UWSGI_SCHEME $scheme;
        }
}

in your routes.py file in /home/www-data/web2py/ configure a setup similar to this.

routers = dict(
    BASE = dict(
        default_application = 'welcome',
        domains = {
            'www.domain1.com' : 'domain1',
            'www.domain2.com' : 'domain2',
            'subdomain.domain2.com' : 'sub',
            },
        applications = ['welcome', 'domain1', 'domain2', 'sub', 'development1', 'admin'],
        controllers = 'DEFAULT'
        ),
    )

For reference I added an example sub domain entry. An important aspect to note from this subdomain entry is that it doesn’t require a server {} value in the /etc/nginx/sites-available/web2py config.

Then simply restart nginx and uwsgi-emperor.

service nginx restart
restart uwsgi-emperor 

References:
Stack Overflow – where I found the necessary nginx information
Web2py URL Rewrite documentation