How to disable HSTS header with HTTP? - .htaccess

I have inserted the following in the .htaccess of my site in order to be admitted to the HSTS preload list:
<ifModule mod_headers.c>
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
</ifModule>
The problem is that when I submit my site, I obtain:
Warning: Unnecessary HSTS header over HTTP.
The HTTP page at
http: //fabriziorocca.it sends an HSTS header. This has no effect over
HTTP, and should be removed.
At the moment I use the following in the .htaccess in order to switch from http to https:
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
How can I solve the problem?
Thank you in advance.

Below your redirect rules add the code:
Header always set Strict-Transport-Security "max-age=31536000;
includeSubDomains; preload" env=HTTPS

I added in htaccess works perfectly for me.
RewriteEngine On
RewriteCond %{HTTPS} off
# First rewrite to HTTPS:
# Don't put www. here. If it is already there it will be included, if not
# the subsequent rule will catch it.
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Now, rewrite any request to the wrong domain to use www.
# [NC] is a case-insensitive match
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Use HTTP Strict Transport Security to force client to use secure connections only
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" "expr=%{HTTPS} == 'on'"
env=HTTPS not works now.

Try with:
<ifModule mod_headers.c>
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" "expr=%{HTTPS} == 'on'"
</ifModule>
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

No...
Error: HTTP redirects to www first
http://domain.fr (HTTP) should immediately redirect to https://domain.fr (HTTPS) before adding the www subdomain. Right now, the first redirect is to https://www.domain.fr/. The extra redirect is required to ensure that any browser which supports HSTS will record the HSTS entry for the top level domain, not just the subdomain.

Related

HSTS header in .htaccess set up, but not working

I set the lines below on .htaccess file for many websites I developed :
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
<if "%{HTTPS} == 'on'">
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
</if>
I also successfully added the concerned domains on https://hstspreload.org/
Unfortunately, all tests I've done (Chrome development tools, https://securityheaders.com) in order to check if HSTS was well operational failed.
All of the domains have a valid SSL certificate installed, for all domains and subdomains.
I also tried to set headers with PHP, same results.
Does anyone know why, and how to make HSTS effective to pass the test ?
Thanks for your help

WWW Redirection in an HTACCESS File

I have an htaccess file for a React app at https://searchglutenfree.com/. I want it to automatically rewrite https://www.searchglutenfree.com/ to https://searchglutenfree.com/ while keeping all the params during the redirection.
I found this great default htaccess template on GitHub (https://gist.github.com/iheartmedia-matt/253ccb6183fdeaa5619f615f2cb5a58b), and getting the www to redirect is the last thing I need. Anyone know what I need to add and where in the file to get the WWW rewrite?
<ifModule mod_rewrite.c>
#######################################################################
# GENERAL #
#######################################################################
# Make apache follow sym links to files
Options +FollowSymLinks
# If somebody opens a folder, hide all files from the resulting folder list
IndexIgnore */*
#######################################################################
# REWRITING #
#######################################################################
# Enable rewriting
RewriteEngine On
# If its not HTTPS
RewriteCond %{HTTPS} off
# Comment out the RewriteCond above, and uncomment the RewriteCond below if you're using a load balancer (e.g. CloudFlare) for SSL
# RewriteCond %{HTTP:X-Forwarded-Proto} !https
# Redirect to the same URL with https://, ignoring all further rules if this one is in effect
RewriteRule ^(.*) https://%{HTTP_HOST}/$1 [R,L]
# If we get to here, it means we are on https://
# If the file with the specified name in the browser doesn't exist
RewriteCond %{REQUEST_FILENAME} !-f
# and the directory with the specified name in the browser doesn't exist
RewriteCond %{REQUEST_FILENAME} !-d
# and we are not opening the root already (otherwise we get a redirect loop)
RewriteCond %{REQUEST_FILENAME} !\/$
# Rewrite all requests to the root
RewriteRule ^(.*) /
</ifModule>
<IfModule mod_headers.c>
# Do not cache sw.js, required for offline-first updates.
<FilesMatch "sw\.js$">
Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform"
Header set Pragma "no-cache"
</FilesMatch>
</IfModule>
If you don’t need this to be dynamic regarding the host name, then I would add a Condition that checks if the host name started with www. after the one that checks for %{HTTPS} off, and add the [OR] flag to the former - and then simply hard-code the host name in the substitution URL of the following Rule.
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.
RewriteRule ^(.*) https://searchglutenfree.com/$1 [R,L]
If you replace everything between the comments # If its not HTTPS and # If we get to here, it means we are on https:// in your .htaccess you had shown above with that, it should work.
In order to set up the desired redirect, www.example.com to example.com or vice versa, you must have an A record for each name.
To redirect users from www to a plain, non-www domain, insert this configuration:
in your .htaccess:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

How do I correctly handle multiple capturing groups in .htaccess?

I'm trying to get:
example.com/curriculum/<curriculum name>/unit/<unit name>/
to rewrite to:
example.com/curriculum/unit/?c=<curriculum name>&u=<unit name>
so far I have:
RewriteRule ^/curriculum/([A-Za-z0-9_-]+)/unit/([A-Za-z0-9_-]+)/?$ https://www.example.com/curriculum/unit/?c=$1&u=$2
Considering that:
RewriteRule ^curriculum/([A-Za-z0-9_-]+)/?$ https://www.example.com/curriculum/?c=$1
works as expected, I assume my syntax is off, as when loading, I just get error 404, with the URL not rewritten from its original format. To clarify, /curriculum/unit does exist.
Any guidance or advice on what I need to do to make this work? Thanks!
Update
Full .htaccess file as requested:
### activate mod_expires
ExpiresActive On
### Expire .gif's 1 month from when they're accessed
ExpiresByType image/gif A2592000
### Expire everything else 1 day from when it's last modified
### (this uses the Alternative syntax)
ExpiresDefault "modification plus 1 day"
### Apply a Cache-Control header to index.html and styles.css
###Cross-Site Scripting protection
Header always set X-Xss-Protection "1; mode=block"
###Disallow websites to frame legacycars - user protection
Header always append X-Frame-Options SAMEORIGIN
<IfModule mod_headers.c>
#No Cache browser revalidates on each request and fetches new version IF contents change based on ETag or Last-Modified response
<FilesMatch "\.(html|php)$">
Header set Cache-Control "no-cache"
</FilesMatch>
#DAY Stock and Cover images expire at the end of each day, but must be checked for changes
<FilesMatch "\.(jpg|jpeg)$">
Header set Cache-Control "max-age=86400, public, must-revalidate"
</FilesMatch>
#WEEK Icons and badges expire after a week
<FilesMatch "\.(ico|png|gif|swf|svg|xml)$">
Header set Cache-Control "max-age=604800, public"
</FilesMatch>
#MONTH Site framework expires after a month, but must be checked for changes
<FilesMatch "\.(js|css|json)$">
Header set Cache-Control "max-age=2628000, public, must-revalidate"
</FilesMatch>
#Hide .credentials
<FilesMatch ".credentials.php">
Order allow,deny
Deny from all
</FilesMatch>
Options +FollowSymLinks -MultiViews
ErrorDocument 404 https://www.example.com/error/404.html
ErrorDocument 403 https:/www.example.com/error/403.html
# Turn mod_rewrite on
RewriteEngine On
#Rewrite curriculum and unit to GET vars
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^curriculum/([\w-]+)/unit/([\w-]+)/?$ curriculum/unit/?c=$1&u=$2 [L,QSA,NC]
RewriteRule ^curriculum/([\w-]+)/?$ curriculum/?c=$1 [L,QSA,NC]
# Externally redirect direct client requests for subdomain-subdirectory URLs
# to subdomain URLs without subdomain-subdirectory URL-path
Redirect permanent /sd_manage/ https://manage.example.com
RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^manage(.*)$ https://manage.example.com [R=301,L]
RewriteRule ^manage/(.*)$ https://manage.example.com/$1 [R=301,L]
# Rewrite root subdomain to www
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L,NE]
# Rewrite valid subdomains to the secure site
RewriteCond %{HTTPS} off
# RewriteCond %{HTTP_HOST} ^(www|manage)\.example\.com$
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
</IfModule>
# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php71” package as the default “PHP” programming language.
<IfModule mime_module>
AddHandler application/x-httpd-ea-php71 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit
You may keep these 2 rewrite rules:
ErrorDocument 404 /error/404.html
ErrorDocument 403 /error/403.html
Options +FollowSymLinks -MultiViews
RewriteEngine On
# Externally redirect direct client requests for subdomain-subdirectory URLs
# to subdomain URLs without subdomain-subdirectory URL-path
RewriteRule ^sd_manage/ https://manage.example.com [L,R=301,NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?example\.com$ [NC]
RewriteRule ^manage(/.*)?$ https://manage.example.com$1 [R=301,L,NC,NE]
# Rewrite root subdomain to www
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
# Rewrite valid subdomains to the secure site
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
#Rewrite curriculum and unit to GET vars
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
RewriteRule ^curriculum/([\w-]+)/?$ curriculum/?c=$1 [L,QSA,NC]
RewriteRule ^curriculum/([\w-]+)/unit/([\w-]+)/?$ curriculum/unit/?c=$1&u=$2 [L,QSA,NC]

Need to redirect to HTTPS using my current htaccess

I want to redirect HTTP and www to https://example.com.
I tried using:
# force HTTPS and www.
RewriteEngine On
RewriteCond %{HTTP_HOST} (?!^www\.)^(.+)$ [OR]
RewriteCond %{HTTPS} off
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L]
But the result is only https://www. - the domain disappeared!
My current .htaccess:
<IfModule mod_rewrite.c>
# REWRITE ENGINE CONFIG
#ExpiresActive On
DirectoryIndex under_construction.html index.html index.php
#Header set Cache-Control "max-age=259200, public"
#ExpiresDefault "access plus 3 days"
#Header unset ETag
#FileETag None
# Expires header for static content
#<FilesMatch "\.(ico|jpg|jpeg|png|gif|js|css|swf|jgz|js.jgz)$">
#Header set Cache-Control "max-age=31536000, public"
#ExpiresDefault "access plus 11 months"
#</FilesMatch>
# Auth for non-public projects
#AuthName "ZEN 2.2 Login"
#AuthType Basic
#AuthUserFile /Applications/MAMP/htdocs/username/.htpasswd
#AuthUserFile F:/wamp/www/username/.htpasswd
#AuthGroupFile /dev/null
#require valid-user
# REWRITE CORE RULES RULES -- PLEASE DON'T MODIFY --
# THESE ARE THE MAIN REWRITES THAT MAKE THE ENTIRE WORLD SPIN
AddDefaultCharset UTF-8
# IF NO IMAGE FOUND
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} \.(gif|jpg|jpeg|png)$
RewriteRule .* resources/static/images/no_image.png [L]
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?page=$1&%{QUERY_STRING} [L,QSA]
RewriteRule ^robots.txt$ resources/static/robots.php [L]
# gZip minified js files
RewriteCond %{HTTP:Accept-Encoding} gzip
RewriteCond %{REQUEST_FILENAME}.jgz -f
RewriteRule (.*)\.js$ $1\.js.jgz [L]
AddType "text/javascript" .js.jgz
AddEncoding gzip .jgz
# gZip minified css files
RewriteCond %{HTTP:Accept-Encoding} gzip
RewriteCond %{REQUEST_FILENAME}.jgz -f
RewriteRule (.*)\.css$ $1\.css.jgz [L]
AddType "text/css" .css.jgz
AddEncoding gzip .jgz
</IfModule>
Need some help adding the redirection to HTTPS and non-WWW to the current .htaccess file.
The problem when using code from here -> https://gist.github.com/vielhuber/f2c6bdd1ed9024023fe4
Is that the redirection is broken, and the result is https://www. only, no domain name is showing.
Try:
# force HTTPS and www.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [OR]
RewriteCond %{HTTPS} !on
RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [R=301,QSA,L]
Some webservers don't create the HTTPS header when http protocol is used. So if HTTPS is not on (is off or null) this condition is true.
# force HTTPS and www.
RewriteEngine On
RewriteCond %{HTTP_HOST} (?!^www\.)^(.+)$ [OR]
RewriteCond %{HTTPS} off
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L]
The problem with this code is, as the preceding comment suggests, it tries to redirect to www, not the domain apex. But it is also fundamentally flawed since the first condition is not always met (when HTTPS is off and www is requested), so the %1 backreference is not always set (so the domain name is omitted from the redirect - as you have found).
If you want a generalised (ie. without explicitly stating the hostname) solution then you would need to do something like the following instead:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\. [OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
The above rule block states... for all requests that are either for the www subdomain OR are for HTTP then redirect to HTTPS, less the www subdomain (if any) at the same URL-path.
The purpose of the 3rd condition - which must always match - is to simply capture the hostname less the www subdomain (if any). This is then referenced using the %1 backreference in the RewriteRule substitution.
NB: Test with a 302 (temporary) redirect first to avoid caching issues.
You will need to clear your browser cache before testing.
UPDATE: it is redirecting to domainname.com:443
That shouldn't be happening with the above directives, unless perhaps the port is explicitly included in the request? (But is that a redirect for http or https?)
You can try changing the 3rd condition to read:
RewriteCond %{HTTP_HOST} ^(?:www\.)?([^:]+)
Or hardcode the canonical hostname, which is arguably preferable and more reliable (without knowing your system). For example:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\. [OR]
RewriteCond %{HTTPS} off
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]
With this hardcoded solution, it cannot possibly redirect to anything other than the canonical URL - regardless of the request or system configuration.
EDIT#1: if I remove the htaccess file completely, the website still redirect to :443 if access from https
To help with debugging, try the following in your .htaccess file and then access https://your-domain.com/. What happens?
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule ^ - [F]
If you see a 403 Forbidden response then your web application would seem to be triggering this redirect. If not and you are still redirected then something in the main server config / virtual host would seem to be triggering the redirect.
EDIT#2: Yes, the response when i browse the https is 403 Forbidden.
That would seem to suggest that your web application is triggering this redirect.
And this would seem to be further backed up by the fact that you only seem to get this malformed redirect when requesting a valid URL, ie. one which only the app knows about. For example, https://example.com/contact (a valid page) is redirecting to http://example.com:443/contact (ERROR), but https://example.com/does-not-exist does not redirect (you get an application error / 404).

.htaccess https breaks rewrite rules

I am experienceing some .htaccess redirect issues.
Mainly I do not care if the user is on https unless I send them there, I have found alot of resources on how to force https, but that is not what I am trying to do.
this is a example of my htaccess:
Options -Indexes
Options -MultiViews
<filesMatch "\.(html|htm|txt|js|htaccess)$">
FileETag None
<ifModule mod_headers.c>
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</ifModule>
</filesMatch>
ErrorDocument 404 /404.php
RewriteEngine On
#RewriteCond %{HTTPS} !=on
#RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#Main site rules
RewriteRule ^about/?$ about.php [NC,L]
I am able to force https using:
#RewriteCond %{HTTPS} !=on
#RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
But then the example rule which redirects to about.php does not work.
How do I allow for https in my redirects?
I also experimented with:
Define servername www.example.com
Define SSL
But I did not understand its function or implementation.

Resources