Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring a subdomain on nginx using namecheap

I bought a domain name using namecheap, for simplicities' sake lets' call it example.com. I am running nginx on a Debian based VPS.

I want to set up the following configuration

  • (www).example.com points : to var/www/blog
  • (www).static.example.com : points to var/www/static

However I can't wrap my head around configuring the subdomain using nginx, or is that something I need to do using Namecheaps control panel?

This is my configuration on Namecheap:

  • @ 111.111.111.111 Record type: A TTL: 1800
  • www example.com Record type: Cname/Alias TTL: 1800

No subdomains are configured, Should I configure subdomains here!?

And here is my nginx configuration:

server {
    root /var/www/blog;
    index index.html index.htm;
    server_name localhost example.com www.example.com;
    location / {
    index index.html index.htm;
   }
}

server {
    root /var/www/static;
    index index.html index.htm;
    server_name static.example.com www.static.example.com;
    location / {
    index index.html index.htm;
}

However this leads to the following:

  • www.example.com points to the correct destination

  • random.example.com points to www.example.com (I don't want this to happen, it should return a 404)

  • static.example.com gives me an error 400. If i look into my logs it can't find the file /var/www/blog/static/index.html, while actually I want it to point to /var/www/static/index.html

like image 427
user3486416 Avatar asked Jun 01 '14 00:06

user3486416


1 Answers

You have to keep in mind that setting up DNS and configuring nginx are entirely different tasks.

The way I like to setup my DNS is to do a CNAME from www and other subdomains back to the original domain, if they are logically the same, and hosted on the same server. (However, technically, it's incorrect, because it means that you specify that all of your domains have MX records, as well as TXT / SPF records showing that they could be used for mail. But noone really cares, so, as long as you don't have your TLD itself as a CNAME, things should be fine.)

You don't see a 404 from random.example.com because the first server becomes your default server. To avoid this, you might want to have an extra server context with a listen directive having a default_server parameter, where you can unconditionally return 404; for all requests.

The reason your final server context might not be working may perhaps be due to a missing listen directive. It usually helps to have an identical listen directive between all of your servers.

like image 51
cnst Avatar answered Sep 22 '22 00:09

cnst