0

I want to redirect domain.com to www.domain.com in apache. But when I try following config It gets double redirect www.www.domain.com

<VirtualHost *:80>
    DocumentRoot /var/www/master/public_html
    ServerName www.domain.com
    ServerAlias domain.com
    RewriteEngine On
    RewriteRule ^(/www/.*) /www/domain.com$1
    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    RewriteCond %{HTTP:X-Forwarded-Proto} =http
    RewriteRule .* https://www.%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]
</VirtualHost>


<VirtualHost *:443>
    DocumentRoot /var/www/master/public_html
    ServerName www.domain.com
    ServerAlias domain.com
    ServerPath /var/www/master/public_html

    RewriteEngine On
    RewriteRule ^(/www/.*) /www/domain.com$1
    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^ %{REQUEST_SCHEME}://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    RewriteCond %{HTTP_ACCEPT} image/webp
    RewriteCond %{REQUEST_URI}  (?i)(.*)(\.jpe?g|\.png)$
    RewriteCond %{DOCUMENT_ROOT}%1.webp -f
    RewriteRule (?i)(.*)(\.jpe?g|\.png)$ %1\.webp [L,T=image/webp,R]
    SSLEngine On
    ServerSignature On
    SSLCertificateFile /etc/ssl/certs/star_domain_com_05_2020.crt
    SSLCertificateKeyFile /etc/ssl/private/star_domain_com_05_2020.key
    SSLCertificateChainFIle /etc/ssl/certs/DigiCertCA.crt
</VirtualHost>

Whats is wrong here ?

This EC2 is behind ELB which has CloudFront at front for serving static contents from S3. In Cloudfront I have set Viewer Protocol Policy : Redirect HTTP to HTTPS

roy
  • 119
  • 1
  • 2
  • 12

1 Answers1

0

Seems a little over-engineered for what you are trying to do. If all you want is a request to example.com to be sent a 301 redirect to www.example.com then the following should work.

<VirtualHost *:80>
    DocumentRoot /var/www/master/public_html

    ServerName www.example.com
    ServerAlias example.com

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
    RewriteRule . https://www.example.com%{REQUEST_URI} [L,R=301]

</VirtualHost>

How this works is, the virtual-host on port 80 will only receive requests where the host-header in the request is either www.example.com or example.com. Then mod_rewrite checks to see if the host-header is equal to example.com, it does this in a case-insensitive fashion. If the condition matches, then the rewrite-rule is called, which sends a 301 redirect to the client, telling it to make the same request to www.example.com.

I am not sure what you are trying to do with SSL, you likely need to duplicate this into the SSL VirtualHost, and add some validation in the :80 host for the case that you have an X-Forwarded-Proto header that matches https, which indicates that the request is behind a layer-7 (http aware) load-balancer that is doing SSL offloading.

ColtonCat
  • 738
  • 3
  • 7