Set up a new virtual host (server block) on your Nginx server.

In one of our previous tutorials we explained How to install and configure LNMP (Nginx, MySQL and PHP) server on a Debian 6 (squeeze) VPS, now we’re going to look at how to set up a new server block (virtual host) for each new domain.

Note: “VirtualHost” is an Apache term. Nginx does not have Virtual hosts, it has “Server Blocks” that use the server_name and listen directives to bind to tcp sockets.

The following script can be used to set up a new server block on your Nginx server.

#!/usr/bin/env bash
# Nginx - new server block
# http://rosehosting.com

# Functions
ok() { echo -e '\e[32m'$1'\e[m'; } # Green
die() { echo -e '\e[1;31m'$1'\e[m'; exit 1; }

# Variables

# Sanity check
[ $(id -g) != "0" ] && die "Script must be run as root."
[ $# != "1" ] && die "Usage: $(basename $0) domainName"

# Create nginx config file
server {
  server_name $1;
  listen 80;
  root $WEB_DIR/$1/public_html;
  access_log $WEB_DIR/$1/logs/access.log;
  error_log $WEB_DIR/$1/logs/error.log;
  index index.html index.php;
  location / {
    try_files \$uri \$uri/ @rewrites;
  location @rewrites {
    rewrite ^ /index.php last;
  location ~* \.(jpg|jpeg|gif|css|png|js|ico|html)$ {
    access_log off;
    expires max;
  location ~ /\.ht {
    deny  all;
  location ~ \.php {
    fastcgi_index index.php;
    fastcgi_split_path_info ^(.+\.php)(.*)$;
    include /etc/nginx/fastcgi_params;
    fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;

# Creating {public,log} directories
mkdir -p $WEB_DIR/$1/{public_html,logs}

# Creating index.html file
cat > $WEB_DIR/$1/public_html/index.html <<EOF
<!DOCTYPE html>
<html lang="en">
        <meta charset="utf-8" />
<body class="container">
        <div id="wrapper"><p>Hello World</p></div>
        <footer>© $(date +%Y)</footer>

# Changing permissions

# Enable site by creating symbolic link

# Restart
echo "Do you wish to restart nginx?"
select yn in "Yes" "No"; do
    case $yn in
        Yes ) /etc/init.d/nginx restart ; break;;
        No ) exit;;

ok "Site Created for $1"

Here’s what it does, in a nutshell:

  1. Creates a new directory for the site (/var/www/DOMAIN.COM/public_html)
  2. Creates a new directory for log files (/var/www/DOMAIN.COM/logs)
  3. Sets correct owner/group.
  4. Creates a simple index.html file to show the site is working.
  5. Asks for restart.

To use the script type:

./nginx_vhost.sh  newdomain.com

The script should work on Debian, Ubuntu and closely related distributions.

PS. If you liked this post please share it with your friends on the social networks using the buttons on the left or simply leave a reply below. Thanks.

Categories: Scripts