Force redirect from http://host.com:8080 to https://host.com with nginx + apache2

I’m using nginx and Apache 2 :

Here is my configuration in nginx:

server {
    
    listen 80;
    server_name hostexemple.com;
    
    root /home/user/web/www/public;

    # Redirect requests directly to Apache
    location / {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_http_version 1.1;
        proxy_set_header        X-Forwarded-Proto $http_x_forwarded_proto;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_pass http://127.0.0.1:8080;
    }


    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/hostexemple.come/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/hostexemple.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

And the config in Apache 2:

<VirtualHost *:8080>
        ServerAdmin xxx@xxx.com
        
        ServerName hostexemple.com
 
        DocumentRoot /home/user/web/www/public
        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /home/user/web/www/public/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Require all granted
        </Directory>
 
        ErrorLog /home/user/logs/error-prod.log
        LogLevel warn
        CustomLog /home/user/logs/access-prod.log combined
 
</VirtualHost>

It works, but what I would like to do is to redirect any requests from http://hostexemple.com:8080 to https://hostexemple.com to prevent any SEO issue.

The config redirects http to https but not http://hostexemple.com:8080 and when I try to redirect it , it causes a redirection loop.

How can I fix that ?

Answer

Ok found it. I don’t know if it’s the right way to do that but I share :

In an htaccess I had to :

RewriteCond %{SERVER_PORT} ^8080$
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://hostexemple.com%{REQUEST_URI} [L,R=301]

To get more feedback, when your put %{HTTP_HOST} you have the port inside causing an infinite loop.

If anyone have a smarter way to get a %{HTTP_HOST} without the port. That could be handy for the next one.

Attribution
Source : Link , Question Author : injetkilo , Answer Author : injetkilo

Leave a Comment