I'm using nginx 1.10.3 for a couple of virtual web servers. Most of them have the same configuration which seems to be simple (redirect non-www to www and redirect http to https) but still I end up with over 100 lines of code for each configuration. Is there a way to DRY this? e.g. not repeat the logging path every time but just one time?
It is not the biggest problem in the world but I'd like to have this cleaned up and don't know how.
Here is the config I use for each virtual server:
# Virtual Host configuration for www.company.com
#
server {
listen 80;
server_name www.company.com;
access_log /var/log/nginx/www.company.com-access.log;
error_log /var/log/nginx/www.company.com-error.log;
root /var/www/www.company.com/current;
index index.html index.htm;
# Let's Encrypt Challenge
location ~ /.well-known {
allow all;
root /var/www/letsencrypt;
}
location / {
rewrite ^/(.*)$ https://www.company.com/$1 permanent;
rewrite ^/$ https://www.company.com/ permanent;
}
}
server {
listen 80;
server_name company.com;
access_log /var/log/nginx/www.company.com-access.log;
error_log /var/log/nginx/www.company.com-error.log;
root /var/www/www.company.com/current;
index index.html index.htm;
# Let's Encrypt Challenge
location ~ /.well-known {
allow all;
root /var/www/letsencrypt;
}
location / {
rewrite ^/(.*)$ https://company.com/$1 permanent;
rewrite ^/$ https://company.com/ permanent;
}
}
server {
listen 443 ssl http2;
server_name company.com;
access_log /var/log/nginx/www.company.com-access.log;
error_log /var/log/nginx/www.company.com-error.log;
# Letsencrypt SSL certificate
ssl_certificate /etc/letsencrypt/live/www.company.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/www.company.com/privkey.pem;
# Connection credentials caching
ssl_session_cache shared:SSL:20m;
ssl_session_timeout 180m;
# Strict Transport Security
# => Tell the client to remember that this is a https site
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
root /var/www/www.company.com/current;
index index.html index.htm;
location / {
rewrite ^/(.*)$ https://www.company.com/$1 permanent;
rewrite ^/$ https://www.company.com/ permanent;
}
}
server {
listen 443 ssl http2;
server_name www.company.com;
access_log /var/log/nginx/www.company.com-access.log;
error_log /var/log/nginx/www.company.com-error.log;
# Letsencrypt SSL certificate
ssl_certificate /etc/letsencrypt/live/www.company.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/www.company.com/privkey.pem;
# Connection credentials caching
ssl_session_cache shared:SSL:20m;
ssl_session_timeout 180m;
# Strict Transport Security
# => Tell the client to remember that this is a https site
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
root /var/www/www.company.com/current;
index index.html index.htm;
location / {
expires 7d;
add_header Cache-Control public;
try_files $uri $uri/ =404;
}
}