Nginx is better than Apache in many ways, however their configurations are very different.

A while ago, a friend pointed one of my site cannot be visited without www in the url, it caused trouble, since both and should be redirected to This was due to the web server configuration problem. With apache it should be vhost setting changes, but with Nginx since it uses special syntax, the adjustment is as follows.

I provide here a complete solution with ssl and php support, this is working with Nginx 1.12.x. The first block is to redirect non https urls, and the second block checks non www url.

server {
    listen       80;
    listen       [::]:80;
    return       301$request_uri;

server {
    listen       443 ssl;
    listen       [::]:443 ssl;
    if ($host = ''){
       return 301$request_uri;
    error_log    /var/log/nginx/ debug;
    # note that these lines are originally from the "location /" block
    root   /srv/www/yoursiteroot;
    index index.php index.html index.htm;

    ssl_certificate   /etc/ssl/certs/1234.pem;
    ssl_certificate_key  /etc/ssl/certs/1234.key;

    ssl_session_timeout 5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;

    location / {
        try_files $uri $uri/ =404;
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /srv/www/yoursiteroot;

    location ~ [^/]\.php(/|$) {
         fastcgi_split_path_info  ^(.+\.php)(/.+)$;
         fastcgi_index            index.php;
         fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
         include                  fastcgi_params;
         fastcgi_param   PATH_INFO       $fastcgi_path_info;
         fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;