I want to test nginx subdomains before uploading config to the server. Can i test it on localhost? I try
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://localhost:8080;
}
}
server {
listen 80;
server_name sub.localhost;
location / {
proxy_pass http://localhost:8080/sub;
}
}
And it does not work. Shoulld i change my hosts file in order to make it work? Also, after uploading site to the server should i change DNS records and add sub.mydomain.com?
Yes, add '127.0.0.1 sub.localhost' to your hosts file. That sub has to be resolved somehow. That should work.
Then once you're ready to go to the net, yes, add an a or cname record for the subdomain sub.
When I use proxy_pass I also include the proxy.conf from nginx.
http://wiki.nginx.org/HttpProxyModule
For your public webserver with its own domain name, you just need to add a Canonical name using a CNAME record in your DNS configuration:
CNAME * example.com.
Once this is done, set your nginx setting
server_name *.example.com example.com;
In your local setup you can keep the same configuration for nginx but unless you have a local DNS setup, you will have to edit your /etc/hosts file and add each subdomain manually. wildcards don't work in the /etc/hosts file.
127.0.0.1 abc.example.com def.example.com ghi.example.com
It is generally recommended to use .local as the namespace for your local domains.
In Linux based OS just to edit as sudo
/etc/hosts
file and change 127.0.0.1 localhost
to 127.0.0.1 *.localhost
.
So at /etc/nginx/sites-enabled/<environment>/<your_project_name>
edit server_name
key as <subdomain>.localhost
.
Reload nginx and networking service.
$ sudo service nginx reload
$ sudo service networking reload
And then try http://<subdomain>.localhost
at url bar.
It works for me.
UPDATE
In my opinion, a better solution is creating a virtual server that only responds if subdomain doesn’t exist, at /etc/nginx/sites-enabled/development/default
, as default server (remember that you can define only one server as default).
server {
listen 80 default_server;
root /var/www/html/errors/404;
server_name *.localhost *.<host-name>;
location / {
index subdomain.html;
}
}
Make sure that in nginx.conf
(generally at /etc/nginx/nginx.conf
) contain include /etc/nginx/sites-enabled/**/*;
to this virtual server work. If not, put it and then run $ sudo service nginx reload
.
In this case don’t is necessary put *.localhost
in /etc/hosts
, but only localhost
.