nginx www to non-www / http to https

How to redirect www to non-www querys and http to https? With the following nginx config file you can achieve this.

nginx config

I configured the webserver with just one server block for port 80 http and port 442 https querys. If the scheme is http it redirects with a 301 redirect to the https version (https to https). If the www prefix is sent, it is getting removed and redirected (www to non-www).

server {
    listen 80;
    listen 443 ssl http2;

    server_name www.mattionline.de mattionline.de;
    access_log /var/log/nginx/access.log;
    error_log  /var/log/nginx/error.log;

    if ( $scheme = "http" ) {
        return 301 https://mattionline.de$request_uri;
    }

    if ($host ~* ^www\.(.*)$) {
        rewrite / $scheme://mattionline.de$request_uri permanent;
    }

    root /var/www/mattionline.de/;
    index index.html index.htm index.php;

    ssl_certificate /etc/letsencrypt/live/mattionline.de/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/mattionline.de/privkey.pem;

    include upstream.conf;
    include caching.conf;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

}

Check if its working

As you can see:

  • http://mattionline.de is getting redirected to https://mattionline.de
  • http://www.mattionline.de is getting redirected to https://mattionline.de
  • https://www.mattionline.de is getting reditected to https://mattionline.de
  • https://mattionline.de is not redirected and a 200 ok http header
nginx www to non-www / http to https

Kommentar verfassen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Nach oben scrollen