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;

    access_log /var/log/nginx/access.log;
    error_log  /var/log/nginx/error.log;

    if ( $scheme = "http" ) {
        return 301$request_uri;

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

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

    ssl_certificate /etc/letsencrypt/live/;
    ssl_certificate_key /etc/letsencrypt/live/;

    include upstream.conf;
    include caching.conf;

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


Check if its working

As you can see:

  • is getting redirected to
  • is getting redirected to
  • is getting reditected to
  • 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