0

I am trying to redirect all HTTP requests to HTTPS for my domains and also want to redirect all requests from DOMAIN.COM to WWW.DOMAIN.COM..

I know this question has been asked many times before and believe me i have tried almost every configuration. I have tried return and redirect directives but nothing works.

I am using Letsencrypt certificate. and the SAN on my cert are like these

Subject Alternative Names DNS: blog.domain.com DNS: domain.com DNS: forum.domain.com DNS: www.domain.com

here's a config that i am using in my server.

    user apache apache;

    worker_processes auto;

    events {
        worker_connections 1024;
        multi_accept on;
        use epoll;
    }


    http {

access_log  /var/log/nginx/access.log;
#   access_log  logs/access_warn.log    warn;

# Basic settings
charset utf-8;
sendfile on;
tcp_nopush on;
tcp_nodelay off;
types_hash_max_size 2048;

fastcgi_cache_path /var/cache/nginxfastcgi levels=1:2 keys_zone=fastcgicache:10m inactive=10m max_size=64m;
fastcgi_cache_key $scheme$request_method$host$request_uri;
fastcgi_cache_lock on;
fastcgi_cache_use_stale error timeout invalid_header updating http_500;
fastcgi_cache_valid 5m;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;


# Enable Open file cache
open_file_cache         max=1000 inactive=20s;
open_file_cache_valid       30s;
open_file_cache_min_uses    2;
open_file_cache_errors      on; 

# Configure Buffer Sizes
client_body_buffer_size     16k;
client_header_buffer_size   8m;
large_client_header_buffers 2   1k;

# Configure Timeouts
client_body_timeout     12;
client_header_timeout       12;

# Use a higher keepalive timeout to reduce the need for repeated handshakes
keepalive_timeout       300;

send_timeout            10;


# Hide NGINX version information
server_tokens off;
server_name_in_redirect off;

# MIME types
include mime.types;

# Add EXTRA MIME types
types {
    application/x-httpd-php .html;
}

default_type application/octet-stream;

gzip                    on;
gzip_disable            "msie6";
gzip_vary               on;
gzip_proxied            any;
gzip_comp_level         4;

# Gzip Min length of file to compress in bytes.
gzip_min_length         500;
gzip_buffers            4 16k;
gzip_http_version       1.1;

# Turn on gzip for all content types that should benefit from it.
gzip_types application/ecmasript;
gzip_types application/javascript;
gzip_types application/json;
gzip_types application/pdf;
gzip_types application/postscript;
gzip_types image/svg+xml;
gzip_types text/css;
gzip_types text/csv;
gzip_types text/plain;
gzip_types text/xml;

# Prevent mobile providers modding site
add_header "Cache-Control" "no-transform";

# The X-Frame-Options header indicates wheather a browser should be allowed
# to render a page within a frame or iframe.
add_header X-Frame-Options SAMEORIGIN;


    server {
        listen 80;
        server_name www.domain.com  domain.com;

        # Redirect all HTTP requests to HTTPS with a 301 Moved         Permanently response.
        return 302 https://www.domain.com$request_uri;
        # rewrite ^(.*) https://www.domain.com$1/ permanent;

    }

    server {
        # listen 443 ssl http2 default_server;
        # listen [::]:443 ssl http2 default_server;

        listen 443 ssl http2;
        server_name www.domain.com   domain.com;

        ## redirect non www to www
        if ($host = 'domain.com' ) {
        rewrite  ^/(.*)$  https://www.domain.com/$1  permanent;
        }   

        ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem;


        # enable session resumption to improve https performance
        ssl_session_cache shared:SSL:50m;
        ssl_session_timeout 1d;

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

        # Diffie-Hellman parameter for DHE ciphersuites, recommended 2048 bits
        ssl_dhparam /etc/ssl/certs/dhparam.pem;

        # enables server-side protection from BEAST attacks
            ssl_prefer_server_ciphers on;

            ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';

        resolver 8.8.8.8;
            ssl_trusted_certificate /etc/letsencrypt/live/domain.com/fullchain.pem;
        ssl_stapling on;
        ssl_stapling_verify on;  

        root /my/webserver/domain.com;

        index index.php index.html index.htm;


location / {

            try_files $uri $uri/ /index.php?$args;

}   


location ~ /(.readme.html|licence.txt) {
            return 404;
}


location ~ /purge(/.*) {
            allow              127.0.0.1;
            deny               all;
                fastcgi_cache_purge fastcgicache "$scheme$request_method$host$1";
}   



location ~\.php$ {

        set $fastcgi_skipcache 0;


            if ($http_x_custom_header) {
                set $fastcgi_skipcache 0;
    }

    # Don't cache the following URL's
    if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") {
                set $fastcgi_skipcache 1;
    }   

    # Don't use the cache for logged in users or recent commenters
    if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
                set $fastcgi_skipcache 1;
    }

    #Don't cache if there is a cookie called PHPSESSID
    if ($http_cookie = "PHPSESSID")
    {
                set $fastcgi_skipcache 1;
    }

    # Bypass cache for POST requests
    if ($request_method = POST) { 
                set $fastcgi_skipcache 1; 
    }

    # Bypass cache for URL with query string
    if ($query_string != "")  { 
                set $fastcgi_skipcache 1; 
    }

    if ($http_cookie ~ "users_login_cookie") {
                set $fastcgi_skipcache 1;
    }


            include fastcgi_params;
            include fastcgi.conf;

            fastcgi_cache fastcgicache;
            fastcgi_cache_valid 200 60m;
            fastcgi_cache_methods GET HEAD;
            # note: adds a HTTP response header "X-Cache" returning HIT/MISS/BYPASS/EXPIRED for cache use status
            add_header X-Fastcgi-Cache $upstream_cache_status;
            fastcgi_cache_bypass $fastcgi_skipcache;
            fastcgi_no_cache $fastcgi_skipcache;

                fastcgi_buffer_size 128k;
                fastcgi_buffers 256 4k;
                fastcgi_busy_buffers_size 256k;
                fastcgi_temp_file_write_size 256k;

            fastcgi_param SCRIPT_FILENAME $request_filename;

            fastcgi_index index.php;
            if (!-f $realpath_root$fastcgi_script_name) {
                return 404;
    }
            fastcgi_pass    127.0.0.1:9000;
}

location ~* \.(php|html)$ {
            access_log on;
            log_not_found on;
            add_header Pragma public;
            add_header Cache-Control "public";
            expires 14d;
}



# Feed
location ~* \.(?:rss|atom)$ {
            expires 1h;
            add_header Cache-Control "public";
}


# Disable favicon.ico logging
location = /favicon.ico {
            log_not_found off;
            access_log off;
}


location ~ ^/(themes/\w+/views) {
        deny  all;
}  


# Disable viewing of hidden files (files starting with a dot)
location ~ /\. {
        deny  all;
        access_log off;
        log_not_found off;
}    


# We don't need .ht files with nginx.
location ~ /\.ht {
        deny all;
}   

# Allow robots and disable logging
location = /robots.txt {
    allow all;
    log_not_found off;
    access_log off;
}

# Enable permalink structures
if (!-e $request_filename) {
    rewrite . /index.php last;
}



location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    access_log off; 
    log_not_found off; 
    expires     30d;
    access_log  off;
    add_header Pragma public; 
    add_header Cache-Control "public"; 
}

location ~* .(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
    access_log  off;
    log_not_found   off;
    add_header  Pragma Public;
    add_header  Cache-Control public;
    expires     max;
}

}

    }
6
  • What is the problem you are having? Oct 23, 2016 at 19:46
  • You have a rewrite configuration that isn't optimal and might cause your issues. Please look at my summary on the optimal configuration: serverfault.com/questions/808346/… Oct 23, 2016 at 20:08
  • Man, you config is like total mess. No wonder it's not working.
    – drookie
    Oct 23, 2016 at 20:54
  • @drookie thanks for the insight but it doesn't look that messy in sublime with proper indentation. I know i should use conf.d/*.conf structure but i prefer it this way. and if you have some suggestion than please guide me.. error i got is "page is not redirecting properly." It keeps shuffling between domin.com and www.domain.com. Oct 24, 2016 at 10:44
  • @MichaelHampton thanks for reply.. the problem is "page is not redirecting properly." It keeps shuffling between domin.com and www.domain.com. I have tried many things but nothing works. Oct 24, 2016 at 10:45

0

You must log in to answer this question.

Browse other questions tagged .