nginx HTTPS serving with same config as HTTP
Is there a way to share configuration directives across two nginx server {}
blocks? I'd like to avoid duplicating the rules, as my site's HTTPS and HTTP content are served with the exact same config.
Currently, it's like this:
server {
listen 80;
...
}
server {
listen 443;
ssl on; # etc.
...
}
Can I do something along the lines of:
server {
listen 80, 443;
...
if(port == 443) {
ssl on; #etc
}
}
You can combine this into one server block like so:
server {
listen 80;
listen 443 default_server ssl;
# other directives
}
Official How-To
To clarify the accepted answer, you need to omit
SSL on;
and you just need the following for nginx version after 0.8.21
listen 443 ssl;
Reference:
Nginx Docs - Configuring A single HTTP/HTTPS server
I don't know of a way like you suggest, but there's certainly an easy and maintainable way.
Move common server settings into a separate file, i.e. "serverFoo.conf" and then include
it in separate server {}
blocks like so:
server {
listen 80;
include serverFoo.conf;
}
server {
listen 443 ssl;
include serverFoo.conf;
}
Expanding on the already helpful answers, here is a more complete example:
server {
# Listen on port 80 and 443
# on both IPv4 and IPv6
listen 80;
listen [::]:80 ipv6only=on;
listen 443 ssl;
listen [::]:443 ipv6only=on ssl;
# Set website folder
root /path/to/your/website;
# Enable SSL
ssl_certificate your-cert.pem;
ssl_certificate_key your-cert.key;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv3:+EXP;
ssl_prefer_server_ciphers on;
}