Skip to content

Instantly share code, notes, and snippets.

@mohamad-supangat
Forked from gsanders5/example.nginx
Last active May 9, 2025 08:01
Show Gist options
  • Save mohamad-supangat/518ddc3c631c230b076b2fe30ffe1ace to your computer and use it in GitHub Desktop.
Save mohamad-supangat/518ddc3c631c230b076b2fe30ffe1ace to your computer and use it in GitHub Desktop.
Automatic nginx virtual subdomains with sub-folders or sub-directories
# Automatic nginx virtual subdomains with sub-folders or sub-directories
#
# Since the original source where I found this code is now offline, I have decided to mirror it here.
# All credit goes to: http://web.archive.org/web/20150307193208/http://www.messaliberty.com/2010/10/automatic-nginx-virtual-subdomains-with-sub-folders-or-sub-directories
#
# Description: In my web root directory I wanted create a folder called photos, and another called
# music using a sftp program. Without manually going back to the config file or to the shell I like to
# be able to access them at photos.nginxdomain.com and music.nginxdomain.com. That is what this config does.
# Redirect visitors from http://nginxdomain.com/ to http://www.nginxdomain.com/
server {
listen 80;
server_name nginxdomain.com;
rewrite ^/(.*) http://www.nginxdomain.com/$1 permanent;
}
# Serve http://www.nginxdomain.com/
server {
listen 80;
server_name www.nginxdomain.com;
root /home/domains/nginxdomain.com/public;
}
# Automatically create subdomains based on directory existence.
server {
listen 80;
server_name ~^(.*)\.nginxdomain\.com$;
# If a directory doesn't exist...
if (!-d /home/domains/nginxdomain.com/public/$1) {
# If a client requests a subdomain but the server does not have a folder to serve, redirect back to the main site.
rewrite . http://www.nginxdomain.com/ redirect;
}
# Sets the correct root
root /home/domains/nginxdomain.com/public/$1;
}
#user http;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
# Load all installed modules
include modules.d/*.conf;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
# HTTPS server
#
server {
listen 443 ssl;
server_name ~^(.*)\.dev\.localhost$;
ssl_certificate /etc/nginx/_wildcard.dev.localhost.pem;
ssl_certificate_key /etc/nginx/_wildcard.dev.localhost-key.pem;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
#
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
location / {
proxy_pass http://localhost:$1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment