FAQ

Page Discussion Edit History

NginxVirtualHostExample

Contents

Edit section: Virtual Hosts Examples Virtual Hosts Examples

Edit section: Two Virtual Hosts, Serving Static Files Two Virtual Hosts, Serving Static Files

http {
  server {
    listen          80;
    server_name     www.domain1.com;
    access_log      logs/domain1.access.log main;
 
    index index.html;
    root  /var/www/domain1.com/htdocs;
  }
 
  server {
    listen          80;
    server_name     www.domain2.com;
    access_log      logs/domain2.access.log main;
 
    index index.html;
    root  /var/www/domain2.com/htdocs;
  }
}

Edit section: A Default Catchall Virtual Host A Default Catchall Virtual Host

http {
  server {
    listen          80 default;
    server_name     _;
    access_log      logs/default.access.log main;
 
    server_name_in_redirect  off;
 
    index index.html;
    root  /var/www/default/htdocs;
  }
}

Edit section: Wildcard Subdomains in a Parent Folder Wildcard Subdomains in a Parent Folder

This is just a really easy way to keep adding new subdomains, or to add new domains automatically when DNS records are pointed at the server. Note that I have included FCGI here as well. If you want to just serve static files, strip out the FCGI config and change the default document to index.html. Rather than creating a new vhost.conf file for every domain, just create one of these:

server {
  # Replace this port with the right one for your requirements
  listen       80;  #could also be 1.2.3.4:80
 
  # Multiple hostnames separated by spaces.  Replace these as well.
  server_name  star.yourdomain.com *.yourdomain.com; #Alternately: _ *  
 
  root /PATH/TO/WEBROOT/$host;
 
  error_page  404 http://yourdomain.com/errors/404.html;
  access_log  logs/star.yourdomain.com.access.log;
 
  index  index.php;
 
  # serve static files directly
  location ~* ^.+\.(jpg|jpeg|gif|css|png|js|ico|html)$ {
    access_log        off;
    expires           30d;
  }
 
  location ~ .php$ {
    # By all means use a different server for the fcgi processes if you need to
    fastcgi_pass   127.0.0.1:YOURFCGIPORTHERE;  
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    fastcgi_param  QUERY_STRING     $query_string;
    fastcgi_param  REQUEST_METHOD   $request_method;
    fastcgi_param  CONTENT_TYPE     $content_type;
    fastcgi_param  CONTENT_LENGTH   $content_length;
    fastcgi_intercept_errors on;
  }
 
  location ~ /\.ht {
    deny  all;
  }
}