Cloudflare flexible SSL and redirects - .htaccess

I'm having some really annoying problems with my domain.
I have Cloudflare flexible SSL on my site, and it makes a https call, IF I type it myself ><
When I try to force https to be used on my site via a .htaccess file I get an internel server error.
I would like all visitors to my site to always be redirected to https://www.example.com even if they type example.com or example.com/index.php etc. + using https on the whole site.
I just can't find the solution to this, so I'm trying stack.
My DNS settings on Cloudflare is an A record that points domain.com to a IP
and a CNAME record that says www.domain.com is an alias of domain.com
I have no page rules added on Cloudflare atm.
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
<FilesMatch "\.(cur|gif|ico|jpe?g|png|svgz?|webp)$">
SetEnvIf Origin ":" IS_CORS
Header set Access-Control-Allow-Origin "*" env=IS_CORS
</FilesMatch>
</IfModule>
</IfModule>
<IfModule mod_headers.c>
<FilesMatch "\.(eot|otf|tt[cf]|woff)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
Options -MultiViews
<IfModule mod_headers.c>
Header set X-UA-Compatible "IE=edge"
# `mod_headers` cannot match based on the content-type, however, this
# header should be send only for HTML pages and not for the other resources
<FilesMatch "\.(appcache|atom|crx|css|cur|eot|f4[abpv]|flv|gif|htc|ico|jpe?g|js|json(ld)?|m4[av]|manifest|map|mp4|oex|og[agv]|opus|otf|pdf|png|rdf|rss|safariextz|svgz?|swf|tt[cf]|vcf|vtt|webapp|web[mp]|woff|xml|xpi)$">
Header unset X-UA-Compatible
</FilesMatch>
</IfModule>
<IfModule mod_mime.c>
# Audio
AddType audio/mp4 m4a f4a f4b
AddType audio/ogg oga ogg opus
# Data interchange
AddType application/json json map
AddType application/ld+json jsonld
AddType application/javascript js
# Video
AddType video/mp4 f4v f4p m4v mp4
AddType video/ogg ogv
AddType video/webm webm
AddType video/x-flv flv
# Web fonts
AddType application/font-woff woff
AddType application/vnd.ms-fontobject eot
AddType application/x-font-ttf ttc ttf
AddType font/opentype otf
AddType image/svg+xml svgz
AddEncoding gzip svgz
# Other
AddType application/octet-stream safariextz
AddType application/x-chrome-extension crx
AddType application/x-opera-extension oex
AddType application/x-web-app-manifest+json webapp
AddType application/x-xpinstall xpi
AddType application/xml atom rdf rss xml
AddType image/webp webp
AddType image/x-icon cur
AddType text/cache-manifest appcache manifest
AddType text/vtt vtt
AddType text/x-component htc
AddType text/x-vcard vcf
</IfModule>
AddDefaultCharset utf-8
<IfModule mod_mime.c>
AddCharset utf-8 .atom .css .js .json .jsonld .rss .vtt .webapp .xml
</IfModule>
#<IfModule mod_rewrite.c>
# Options +FollowSymlinks
# Options +SymLinksIfOwnerMatch
# RewriteEngine On
# REDIRECT /folder/index.php to /folder/
# RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+/)*index\.php\ HTTP/
# RewriteRule ^(([^/]+/)*)index\.php$ http://www.domain.dk/$1 [R=301,L]
#</IfModule>
#<IfModule mod_rewrite.c>
# RewriteCond %{HTTPS} !=on
# RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
# RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
#</IfModule>
#<IfModule mod_rewrite.c>
# RewriteCond %{HTTPS} !=on
# RewriteCond %{HTTP_HOST} !^www\. [NC]
# RewriteCond %{SERVER_ADDR} !=127.0.0.1
# RewriteCond %{SERVER_ADDR} !=::1
# RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
#</IfModule>
<IfModule mod_autoindex.c>
Options -Indexes
</IfModule>
<IfModule mod_rewrite.c>
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]
</IfModule>
<FilesMatch "(^#.*#|\.(bak|config|dist|fla|in[ci]|log|psd|sh|sql|sw[op])|~)$">
# Apache < 2.3
<IfModule !mod_authz_core.c>
Order allow,deny
Deny from all
Satisfy All
</IfModule>
# Apache ≥ 2.3
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
</FilesMatch>
<IfModule mod_headers.c>
Header set X-Content-Type-Options "nosniff"
</IfModule>
#<IfModule mod_rewrite.c>
# RewriteCond %{SERVER_PORT} !^443
# RewriteRule ^ https://www.domain.dk%{REQUEST_URI} [R=301,L]
#</IfModule>
<IfModule mod_deflate.c>
# Force compression for mangled headers.
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
</IfModule>
</IfModule>
# Compress all output labeled with one of the following MIME-types
# (for Apache versions below 2.3.7, you don't need to enable `mod_filter`
# and can remove the `<IfModule mod_filter.c>` and `</IfModule>` lines
# as `AddOutputFilterByType` is still in the core directives).
<IfModule mod_filter.c>
AddOutputFilterByType DEFLATE application/atom+xml \
application/javascript \
application/json \
application/ld+json \
application/rss+xml \
application/vnd.ms-fontobject \
application/x-font-ttf \
application/x-web-app-manifest+json \
application/xhtml+xml \
application/xml \
font/opentype \
image/svg+xml \
image/x-icon \
text/css \
text/html \
text/plain \
text/x-component \
text/xml
</IfModule>
</IfModule>
<IfModule mod_headers.c>
Header set Cache-Control "no-transform"
</IfModule>
<IfModule mod_headers.c>
Header unset ETag
</IfModule>
FileETag None
#<IfModule mod_expires.c>
#ExpiresActive On
#ExpiresByType image/jpg "access 1 year"
#ExpiresByType image/jpeg "access 1 year"
#ExpiresByType image/gif "access 1 year"
#ExpiresByType image/png "access 1 year"
#ExpiresByType text/css "access 1 month"
#ExpiresByType text/html "access 1 month"
#ExpiresByType application/pdf "access 1 month"
#ExpiresByType text/x-javascript "access 1 month"
#ExpiresByType application/x-shockwave-flash "access 1 month"
#ExpiresByType image/x-icon "access 1 year"
#ExpiresDefault "access 1 month"
#</IfModule>

From CloudFlare's knowledge base.
RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
RewriteRule ^(.*)$ https://www.domain.com$1 [L]
See https://support.cloudflare.com/hc/en-us/articles/200170536-How-do-I-redirect-HTTPS-traffic-with-Flexible-SSL-and-Apache-
Just did this myself, works like a charm.

As stated here On Cloudflare Official Support Site
So I'll walk you through what I did, (as of 16-JUN-2016)
Since a picture speaks a thousand words. See Below
And you are done. It should start redirecting to https outright.

Try the following rewrite rule:
<IfModule mod_rewrite.c>
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]
</IfModule>
Also please check that you have an SSL version of your virtual directory enabled in your httpd.conf/apache.conf file.
How are you managing the domain name? Through a control panel or through command line? Which class of cloud flare are you using? Do you have your own SSL certificate installed on the server?

the .htaccess didn't work for me either (neither did creating a rule with force https option).
What worked is I created a rewrite rule on CloudFlare to rewrite from http://yourdomain.com/* to https://yourdomain.com/$1 and that fixed the issues (it took about half an hour to kick in though).

Here's what worked for me:
#Victor Häggqvist's htaccess rules combines with #Mohd Abdul Mujib's page rules (with * also in beginning of rule, though).
RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
RewriteRule ^(.*)$ https://www.domain.com$1 [L]
------
http://*yourdomain.com/*
As per Cloudflare's manual, the protocol must be http in the above for it to work.
I added a pure html page to Cloudflare and got too many redirects, but the above helped. Now I will go and install Wordpress on the site.
These are the links I gathered for my journey, in case they are helpful to someone else, too.
https://support.cloudflare.com/hc/en-us/articles/200170536-How-do-I-redirect-HTTPS-traffic-with-Flexible-SSL-and-Apache-
https://blog.cloudflare.com/flexible-ssl-wordpress-fixing-mixed-content-errors/
https://support.cloudflare.com/hc/en-us/articles/201717894-Using-CloudFlare-and-WordPress-Five-Easy-First-Steps
https://support.cloudflare.com/hc/en-us/articles/203487280--How-do-I-fix-the-infinite-redirect-loop-error-after-enabling-Flexible-SSL-with-WordPress-

Related

Typo3 V9 redirect strips virtual subfolder

I have a Typo3 V 9.5.30 installation. In this system runs 2 sites with different domains. Both are configured as //domain.tld.
When i call it with www. it redirects to non-www that works. When i call it like www.domain.tld/subfolder (not an existing folder, but an configured static route to an subpage in the system) it will be redirect to domain.tld/index.php. Why this happens? In the htaccess i add the folowing rules:
# ssl
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# www
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
following redirect i want:
http://www.domain.tld/subfolder -> https://domain.tld/subfolder
Im out of any idea, anyone can help?
my .htaccess looks like:
#####
#
# Example .htaccess file for TYPO3 CMS - for use with Apache Webserver
#
# This file includes settings for the following configuration options:
#
# - Compression
# - Caching
# - MIME types
# - Cross Origin requests
# - Rewriting and Access
# - Miscellaneous
# - PHP optimisation
#
# If you want to use it, you have to copy it to the root folder of your TYPO3 installation (if its
# not there already) and rename it to '.htaccess'. To make .htaccess files work, you might need to
# adjust the 'AllowOverride' directive in your Apache configuration file.
#
# IMPORTANT: You may need to change this file depending on your TYPO3 installation!
# Consider adding this file's content to your webserver's configuration directly for speed improvement
#
# Lots of the options are taken from https://github.com/h5bp/html5-boilerplate/blob/master/dist/.htaccess
#
####
### Begin: Compression ###
# Compressing resource files will save bandwidth and so improve loading speed especially for users
# with slower internet connections. TYPO3 can compress the .js and .css files for you.
# *) Uncomment the following lines and
# *) Set $GLOBALS['TYPO3_CONF_VARS']['BE']['compressionLevel'] = 9 for the Backend
# *) Set $GLOBALS['TYPO3_CONF_VARS']['FE']['compressionLevel'] = 9 together with the TypoScript properties
# config.compressJs and config.compressCss for GZIP compression of Frontend JS and CSS files.
#<FilesMatch "\.js\.gzip$">
# AddType "text/javascript" .gzip
#</FilesMatch>
#<FilesMatch "\.css\.gzip$">
# AddType "text/css" .gzip
#</FilesMatch>
#AddEncoding gzip .gzip
<IfModule mod_deflate.c>
# Force compression for mangled `Accept-Encoding` request headers
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
</IfModule>
</IfModule>
# Compress all output labeled with one of the following media types.
#
# (!) For Apache versions below version 2.3.7 you don't need to
# enable `mod_filter` and can remove the `<IfModule mod_filter.c>`
# and `</IfModule>` lines as `AddOutputFilterByType` is still in
# the core directives.
#
# https://httpd.apache.org/docs/current/mod/mod_filter.html#addoutputfilterbytype
<IfModule mod_filter.c>
AddOutputFilterByType DEFLATE application/atom+xml \
application/javascript \
application/json \
application/ld+json \
application/manifest+json \
application/rdf+xml \
application/rss+xml \
application/schema+json \
application/vnd.geo+json \
application/vnd.ms-fontobject \
application/x-font-ttf \
application/x-javascript \
application/x-web-app-manifest+json \
application/xhtml+xml \
application/xml \
font/eot \
font/opentype \
image/bmp \
image/svg+xml \
image/vnd.microsoft.icon \
image/x-icon \
text/cache-manifest \
text/css \
text/html \
text/javascript \
text/plain \
text/vcard \
text/vnd.rim.location.xloc \
text/vtt \
text/x-component \
text/x-cross-domain-policy \
text/xml
</IfModule>
<IfModule mod_mime.c>
AddEncoding gzip svgz
</IfModule>
</IfModule>
### End: Compression ###
### Begin: Browser caching of resource files ###
# This affects Frontend and Backend and increases performance.
<IfModule mod_expires.c>
ExpiresActive on
ExpiresDefault "access plus 1 month"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/json "access plus 0 seconds"
ExpiresByType application/ld+json "access plus 0 seconds"
ExpiresByType application/schema+json "access plus 0 seconds"
ExpiresByType application/vnd.geo+json "access plus 0 seconds"
ExpiresByType application/xml "access plus 0 seconds"
ExpiresByType text/xml "access plus 0 seconds"
ExpiresByType image/vnd.microsoft.icon "access plus 1 week"
ExpiresByType image/x-icon "access plus 1 week"
ExpiresByType text/x-component "access plus 1 month"
ExpiresByType text/html "access plus 0 seconds"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType application/x-javascript "access plus 1 year"
ExpiresByType text/javascript "access plus 1 year"
ExpiresByType application/manifest+json "access plus 1 week"
ExpiresByType application/x-web-app-manifest+json "access plus 0 seconds"
ExpiresByType text/cache-manifest "access plus 0 seconds"
ExpiresByType audio/ogg "access plus 1 month"
ExpiresByType image/bmp "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/svg+xml "access plus 1 month"
ExpiresByType image/webp "access plus 1 month"
ExpiresByType video/mp4 "access plus 1 month"
ExpiresByType video/ogg "access plus 1 month"
ExpiresByType video/webm "access plus 1 month"
ExpiresByType application/atom+xml "access plus 1 hour"
ExpiresByType application/rdf+xml "access plus 1 hour"
ExpiresByType application/rss+xml "access plus 1 hour"
ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
ExpiresByType font/eot "access plus 1 month"
ExpiresByType font/opentype "access plus 1 month"
ExpiresByType application/x-font-ttf "access plus 1 month"
ExpiresByType application/font-woff "access plus 1 month"
ExpiresByType application/x-font-woff "access plus 1 month"
ExpiresByType font/woff "access plus 1 month"
ExpiresByType application/font-woff2 "access plus 1 month"
ExpiresByType text/x-cross-domain-policy "access plus 1 week"
</IfModule>
### End: Browser caching of resource files ###
### Begin: MIME types ###
# Proper MIME types for all files
<IfModule mod_mime.c>
# Data interchange
AddType application/atom+xml atom
AddType application/json json map topojson
AddType application/ld+json jsonld
AddType application/rss+xml rss
AddType application/vnd.geo+json geojson
AddType application/xml rdf xml
# JavaScript
AddType application/javascript js
# Manifest files
AddType application/manifest+json webmanifest
AddType application/x-web-app-manifest+json webapp
AddType text/cache-manifest appcache
# Media files
AddType audio/mp4 f4a f4b m4a
AddType audio/ogg oga ogg opus
AddType image/bmp bmp
AddType image/svg+xml svg svgz
AddType image/webp webp
AddType video/mp4 f4v f4p m4v mp4
AddType video/ogg ogv
AddType video/webm webm
AddType video/x-flv flv
AddType image/x-icon cur ico
# Web fonts
AddType application/font-woff woff
AddType application/font-woff2 woff2
AddType application/vnd.ms-fontobject eot
AddType application/x-font-ttf ttc ttf
AddType font/opentype otf
# Other
AddType application/octet-stream safariextz
AddType application/x-bb-appworld bbaw
AddType application/x-chrome-extension crx
AddType application/x-opera-extension oex
AddType application/x-xpinstall xpi
AddType text/vcard vcard vcf
AddType text/vnd.rim.location.xloc xloc
AddType text/vtt vtt
AddType text/x-component htc
</IfModule>
# UTF-8 encoding
AddDefaultCharset utf-8
<IfModule mod_mime.c>
AddCharset utf-8 .atom .css .js .json .manifest .rdf .rss .vtt .webapp .webmanifest .xml
</IfModule>
### End: MIME types ###
### Begin: Cross Origin ###
# Send the CORS header for images when browsers request it.
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
<FilesMatch "\.(bmp|cur|gif|ico|jpe?g|png|svgz?|webp)$">
SetEnvIf Origin ":" IS_CORS
Header set Access-Control-Allow-Origin "*" env=IS_CORS
</FilesMatch>
</IfModule>
</IfModule>
# Allow cross-origin access to web fonts.
<IfModule mod_headers.c>
<FilesMatch "\.(eot|otf|tt[cf]|woff2?)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
### End: Cross Origin ###
### Begin: Rewriting and Access ###
# You need rewriting, if you use a URL-Rewriting extension (RealURL, CoolUri).
<IfModule mod_rewrite.c>
# Enable URL rewriting
RewriteEngine On
# Store the current location in an environment variable CWD to use
# mod_rewrite in .htaccess files without knowing the RewriteBase
RewriteCond $0#%{REQUEST_URI} ([^#]*)#(.*)\1$
RewriteRule ^.*$ - [E=CWD:%2]
# Rules to set ApplicationContext based on hostname
#RewriteCond %{HTTP_HOST} ^dev\.example\.com$
#RewriteRule .? - [E=TYPO3_CONTEXT:Development]
#RewriteCond %{HTTP_HOST} ^staging\.example\.com$
#RewriteRule .? - [E=TYPO3_CONTEXT:Production/Staging]
#RewriteCond %{HTTP_HOST} ^www\.example\.com$
#RewriteRule .? - [E=TYPO3_CONTEXT:Production]
# Rule for versioned static files, configured through:
# - $GLOBALS['TYPO3_CONF_VARS']['BE']['versionNumberInFilename']
# - $GLOBALS['TYPO3_CONF_VARS']['FE']['versionNumberInFilename']
# IMPORTANT: This rule has to be the very first RewriteCond in order to work!
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)\.(\d+)\.(php|js|css|png|jpg|gif|gzip)$ %{ENV:CWD}$1.$3 [L]
# Access block for folders
RewriteRule _(?:recycler|temp)_/ - [F]
RewriteRule fileadmin/templates/.*\.(?:txt|ts)$ - [F]
RewriteRule ^(?:vendor|typo3_src|typo3temp/var) - [F]
RewriteRule (?:typo3conf/ext|typo3/sysext|typo3/ext)/[^/]+/(?:Configuration|Resources/Private|Tests?|Documentation|docs?)/ - [F]
# Block access to all hidden files and directories with the exception of
# the visible content from within the `/.well-known/` hidden directory (RFC 5785).
RewriteCond %{REQUEST_URI} "!(^|/)\.well-known/([^./]+./?)+$" [NC]
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule (?:^|/)\. - [F]
# Stop rewrite processing, if we are in the typo3/ directory or any other known directory
# NOTE: Add your additional local storages here
RewriteRule ^(?:typo3/|fileadmin/|typo3conf/|typo3temp/|uploads/|favicon\.ico) - [L]
# If the file/symlink/directory does not exist => Redirect to index.php.
# For httpd.conf, you need to prefix each '%{REQUEST_FILENAME}' with '%{DOCUMENT_ROOT}'.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^.*$ %{ENV:CWD}index.php [QSA,L]
</IfModule>
# Access block for files
# Apache < 2.3
<IfModule !mod_authz_core.c>
<FilesMatch "(?i:^\.|^#.*#|^(?:ChangeLog|ToDo|Readme|License)(?:\.md|\.txt)?|^composer\.(?:json|lock)|^ext_conf_template\.txt|^ext_typoscript_constants\.txt|^ext_typoscript_setup\.txt|flexform[^.]*\.xml|locallang[^.]*\.(?:xml|xlf)|\.(?:bak|co?nf|cfg|ya?ml|ts|typoscript|tsconfig|dist|fla|in[ci]|log|sh|sql(?:\..*)?|sqlite(?:\..*)?|sw[op]|git.*|rc)|.*~)$">
Order allow,deny
Deny from all
Satisfy All
</FilesMatch>
</IfModule>
# Apache ≥ 2.3
<IfModule mod_authz_core.c>
<If "%{REQUEST_URI} =~ m#(?i:/\.|/\x23.*\x23|/(?:ChangeLog|ToDo|Readme|License)(?:\.md|\.txt)?|/composer\.(?:json|lock)|/ext_conf_template\.txt|/ext_typoscript_constants\.txt|/ext_typoscript_setup\.txt|flexform[^.]*\.xml|locallang[^.]*\.(?:xml|xlf)|\.(?:bak|co?nf|cfg|ya?ml|ts|typoscript|tsconfig|dist|fla|in[ci]|log|sh|sql(?:\..*)?|sqlite(?:\..*)?|sw[op]|git.*|rc)|.*~)$#">
Require all denied
</If>
</IfModule>
# Block access to vcs directories
<IfModule mod_alias.c>
RedirectMatch 404 /\.(?:git|svn|hg)/
</IfModule>
### End: Rewriting and Access ###
### Begin: Miscellaneous ###
# 404 error prevention for non-existing redirected folders
Options -MultiViews
# Make sure that directory listings are disabled.
<IfModule mod_autoindex.c>
Options -Indexes
</IfModule>
<IfModule mod_headers.c>
# Force IE to render pages in the highest available mode
Header set X-UA-Compatible "IE=edge"
<FilesMatch "\.(appcache|crx|css|eot|gif|htc|ico|jpe?g|js|m4a|m4v|manifest|mp4|oex|oga|ogg|ogv|otf|pdf|png|safariextz|svgz?|ttf|vcf|webapp|webm|webp|woff2?|xml|xpi)$">
Header unset X-UA-Compatible
</FilesMatch>
# Reducing MIME type security risks
Header set X-Content-Type-Options "nosniff"
</IfModule>
# ETag removal
<IfModule mod_headers.c>
Header unset ETag
</IfModule>
FileETag None
### End: Miscellaneous ###
# Add your own rules here.
# ssl
#RewriteCond %{HTTPS} off
#RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# www
#RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
#RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
You've put the directives in the wrong place. These redirects need to go at the top of the file, not at the end.
By placing these directives at the end, after the front-controller, the request is internally rewritten to /index.php before the redirect occurs so ends up redirecting to /index.php, not the URL being requested.
You can literally just move these two rules to the very top of the .htaccess file. You do not need to repeat the RewriteEngine directive.

Apache2 is looping because of timthumb file

I have an apache2 server setup with the following .htaccess file at /
<IfModule mod_rewrite.c>
<IfModule mod_env.c>
SetEnv HTTP_MOD_REWRITE On
</IfModule>
RewriteEngine on
#REDIRE HTTPS
#RewriteCond %{HTTPS} off
#RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
#REDIR WWW
#RewriteCond %{HTTP_HOST} !^www\.
#RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L,QSA]
#resize photos
RewriteRule ^photos_(\d*?)x(\d*?)\/(.*)(.jpg|.jpeg|.png|.gif)$ %{ENV:REWRITEBASE}/lib/timthumb/timthumb.php?src=/photos/$3$4&w=$1&h=$2&zc=1 [NC,L]
#RewriteRule ^photos_ext_(\d*?)x(\d*?)\/http([s]*).*?\/(.*)(.jpg|.jpeg|.png|.gif)$ %{ENV:REWRITEBASE}/lib/timthumb/timthumb.php?src=http$3://$4$5&w=$1&h=$2&zc=1 [NC,L]
#RewriteRule ^photos_ext_(\d*?)\/http([s]*).*?\/(.*)(.jpg|.jpeg|.png|.gif)$ %{ENV:REWRITEBASE}/lib/timthumb/timthumb.php?src=http$2://$3$4&w=$1&h=$2&zc=1 [NC,L]
RewriteRule ^photos_(\d*?)\/(.*)(.jpg|.jpeg|.png|.gif)$ %{ENV:REWRITEBASE}/lib/timthumb/timthumb.php?src=/photos/$2$3&w=$1&h=$1&zc=1 [NC,L]
RewriteRule ^visuels_(\d*?)\/(.*)(.jpg|.jpeg|.png|.gif)$ %{ENV:REWRITEBASE}/lib/timthumb/timthumb.php?src=/visuels/$2$3&w=$1&h=$1&zc=1 [NC,L]
#js traductions
RewriteRule ^themes\/.*?\/js\/traduction.js$ %{ENV:REWRITEBASE}/traductionjs [NC,L,R=301]
# Dispatcher
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ %{ENV:REWRITEBASE}index.php [NC,L]
</IfModule>
<IfModule mod_php5.c>
php_value short_open_tag 1
</IfModule>
#<FilesMatch "\.(js)$">
#Header set Access-Control-Allow-Origin "*"
#</FilesMatch>
#optimisations
Options -Indexes
ServerSignature Off
SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/css text/javascript application/javascript application/x-javascript font/ttf application/x-font-ttf font/otf application/x-font-otf font/opentype image/svg+xml application/x-httpd-php
#Pour les navigateurs incompatibles
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
#les proxies doivent donner le bon contenu
Header append Vary User-Agent env=!dont-vary
<IfModule mod_headers.c>
Header always set X-FRAME-OPTIONS "SAMEORIGIN"
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Content-Type-Options "nosniff"
</IfModule>
<ifModule mod_php5.c>
php_value zlib.output_compression 16386
php_value zlib.output_compression_level 5
</ifModule>
FileETag none
<IfModule mod_headers.c>
Header unset ETag
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 week"
ExpiresByType image/gif "access plus 1 week"
ExpiresByType image/jpeg "access plus 1 week"
ExpiresByType image/png "access plus 1 week"
ExpiresByType image/x-icon "access plus 1 week"
ExpiresByType application/x-shockwave-flash "access plus 1 week"
ExpiresByType text/css "access plus 0 seconds"
ExpiresByType text/javascript "access plus 0 seconds"
ExpiresByType application/x-javascript "access plus 0 seconds"
</IfModule>
#No cache for DEV mode
<filesMatch "\.(js|css)$">
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>
and the following proxy pass in 000-default.conf
<VirtualHost *:*>
ProxyPreserveHost On
ProxyPass /wallet http://wallet/
ProxyPassReverse /wallet http://wallet/
ServerName localhost
</VirtualHost>
that proxies a docker application to from /wallet to http://wallet.
When I now access an URL that looks like this http://localhost/series/adventure/adult/helloworld2 I get the following error after a while:
www_1 | [Thu Nov 01 16:02:49.226185 2018] [mpm_prefork:error]
[pid 1] AH00161: server reached MaxRequestWorkers setting, consider raising the MaxRequestWorkers setting
www_1 | localhost:80 127.0.0.1 - - [01/Nov/2018:16:02:47 +0000] "GET /lib/timthumb/timthumb.php?src=/photos/logo-default.jpg&w=300&h=300&zc=2 HTTP/1.0" 400 811 "-" "-"
www_1 | localhost:80 127.0.0.1 - - [01/Nov/2018:16:02:47 +0000] "GET /lib/timthumb/timthumb.php?src=/photos/logo-default.jpg&w=300&h=300&zc=2 HTTP/1.0" 400 811 "-" "-"
www_1 | localhost:80 127.0.0.1 - - [01/Nov/2018:16:02:47 +0000] "GET /lib/timthumb/timthumb.php?src=/photos/logo-default.jpg&w=300&h=300&zc=2 HTTP/1.0" 400 811 "-" "-"
www_1 | localhost:80 127.0.0.1 - - [01/Nov/2018:16:02:47 +0000] "GET /lib/timthumb/timthumb.php?src=/photos/logo-default.jpg&w=300&h=300&zc=2 HTTP/1.0" 400 811 "-" "-"
this goes on forever
After that, the apache2 server is not accessible anymore and I need to restart it. I didn't find anything on the web but already tried to set mpm_event.conf and other parameters. Fundamentally I think there is a loop somewhere in my configurations. I can't figure out where though. I can post the docker file, but it's nothing special.
There are two lines that get called on startup of the php script:
define ('NOT_FOUND_IMAGE',
"http://".$_SERVER["HTTP_HOST"].'/lib/timthumb/timthumb.php?src=/photos/'.$config["image_default"].'&w='.$_GET["w"].'&h='.$_GET["h"].'&zc=2');
define ('ERROR_IMAGE', "http://".$_SERVER["HTTP_HOST"].'/lib/timthumb/timthumb.php?src=/photos/'.$config["image_default"].'&w='.$_GET["w"].'&h='.$_GET["h"].'&zc=2');

Magento http to https in .htaccess issues

I have an issue on a Magento store .htaccess . Right now all http urls are redirecting to root domain. See the whole file below. What should I change remove so the old urls (http version) will redirect to
the new ones. I tried to remove this : RewriteRule .* index.php [L] but the sites breaks and If I insert a 301 R it comes with a redirection loop.
RewriteOptions inherit
############################################
## uncomment these lines for CGI mode
## make sure to specify the correct cgi php binary file name
## it might be /cgi-bin/php-cgi
# Action php5-cgi /cgi-bin/php5-cgi
# AddHandler php5-cgi .php
############################################
## GoDaddy specific options
# Options -MultiViews
## you might also need to add this line to php.ini
## cgi.fix_pathinfo = 1
## if it still doesn't work, rename php.ini to php5.ini
############################################
## this line is specific for 1and1 hosting
#AddType x-mapp-php5 .php
#AddHandler x-mapp-php5 .php
############################################
## default index file
DirectoryIndex index.php
<IfModule mod_php5.c>
############################################
## adjust memory limit
# php_value memory_limit 64M
php_value memory_limit 256M
php_value max_execution_time 18000
############################################
## disable magic quotes for php request vars
php_flag magic_quotes_gpc off
############################################
## disable automatic session start
## before autoload was initialized
php_flag session.auto_start off
############################################
## enable resulting html compression
php_flag zlib.output_compression on
###########################################
# disable user agent verification to not break multiple image upload
php_flag suhosin.session.cryptua off
###########################################
# turn off compatibility with PHP4 when dealing with objects
php_flag zend.ze1_compatibility_mode Off
</IfModule>
<IfModule mod_security.c>
###########################################
# disable POST processing to not break multiple image upload
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>
<IfModule mod_deflate.c>
############################################
## enable apache served files compression
## http://developer.yahoo.com/performance/rules.html#gzip
# Insert filter on all content
###SetOutputFilter DEFLATE
# Insert filter on selected content types only
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript
# Netscape 4.x has some problems...
BrowserMatch ^Mozilla/4 gzip-only-text/html
# Netscape 4.06-4.08 have some more problems
BrowserMatch ^Mozilla/4\.0[678] no-gzip
# MSIE masquerades as Netscape, but it is fine
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
# Don't compress images
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
# Make sure proxies don't deliver the wrong content
Header append Vary User-Agent env=!dont-vary
</IfModule>
<IfModule mod_ssl.c>
############################################
## make HTTPS env vars available for CGI mode
SSLOptions StdEnvVars
</IfModule>
<IfModule mod_rewrite.c>
############################################
## enable rewrites
Options +FollowSymLinks
RewriteEngine on
############################################
## you can put here your magento root folder
## path relative to web root
#RewriteBase /magento/
############################################
## uncomment next line to enable light API calls processing
# RewriteRule ^api/([a-z][0-9a-z_]+)/?$ api.php?type=$1 [QSA,L]
############################################
## rewrite API2 calls to api.php (by now it is REST only)
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteRule ^api/rest api.php?type=rest [QSA,L]
############################################
## workaround for HTTP authorization
## in CGI environment
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
############################################
## TRACE and TRACK HTTP methods disabled to prevent XSS attacks
RewriteCond %{REQUEST_METHOD} ^TRAC[EK]
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteRule .* - [L,R=405]
############################################
## redirect for mobile user agents
#RewriteCond %{REQUEST_URI} !^/mobiledirectoryhere/.*$
#RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
#RewriteRule ^(.*)$ /mobiledirectoryhere/ [L,R=302]
############################################
## always send 404 on missing files in these folders
############################################
## never rewrite for existing files, directories and links
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
############################################
## rewrite everything else to index.php
RewriteRule .* index.php [L]
############################################
## Prevent character encoding issues from server overrides
## If you still have problems, use the second line instead
AddDefaultCharset Off
#AddDefaultCharset UTF-8
<IfModule mod_expires.c>
############################################
## Add default Expires header
## http://developer.yahoo.com/performance/rules.html#expires
ExpiresDefault "access plus 1 month"
</IfModule>
############################################
## By default allow all access
Order allow,deny
Allow from all
###########################################
## Deny access to release notes to prevent disclosure of the installed Magento version
<Files RELEASE_NOTES.txt>
order allow,deny
deny from all
</Files>
############################################
## If running in cluster environment, uncomment this
## http://developer.yahoo.com/performance/rules.html#etags
#FileETag none
###########################################
## Deny access to cron.php
<Files cron.php>
############################################
## uncomment next lines to enable cron access with base HTTP authorization
## http://httpd.apache.org/docs/2.2/howto/auth.html
##
## Warning: .htpasswd file should be placed somewhere not accessible from the web.
## This is so that folks cannot download the password file.
## For example, if your documents are served out of /usr/local/apache/htdocs
## you might want to put the password file(s) in /usr/local/apache/.
#AuthName "Cron auth"
#AuthUserFile ../.htpasswd
#AuthType basic
#Require valid-user
############################################
Order allow,deny
Deny from all
</Files>
############################################
## compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
# Or, compress certain file types by extension:
<files *.html>
SetOutputFilter DEFLATE
</files>
###########################################
# Leverage browser caching using mod_expires #
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresDefault "access plus 2 days"
</IfModule>
# End of Leverage browser caching using mod_expires #

how to remove www from domain name and enforce https?

I wan to achieve two things
remove www from domain name
enforce https
i.e.
http:// www.example.org should be redirect to https://example.org
https:// www.example.org should be redirect to https://example.org
UPDATE:
I am currently using following .htaccess rule
<IfModule mod_rewrite.c>
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
</IfModule>
This rule does remove the www from url if present, I redirects the user to https. This happens only when I have www in url. If I access my site with http://exampl.org it doesn't redirect it to https. How can I achieve both?
1) remove www from url
2) enforece https
Here is my htaccess file, I have been trying the mentioned answers but doesn't seems to be working
# ----------------------------------------------------------------------
# Better website experience for IE users
# ----------------------------------------------------------------------
# Force the latest IE version, in various cases when it may fall back to IE7 mode
# github.com/rails/rails/commit/123eb25#commitcomment-118920
# Use ChromeFrame if it's installed for a better experience for the poor IE folk
<IfModule mod_headers.c>
Header set X-UA-Compatible "IE=Edge,chrome=1"
# mod_headers can't match by content-type, but we don't want to send this header on *everything*...
<FilesMatch "\.(js|css|gif|png|jpe?g|pdf|xml|oga|ogg|m4a|ogv|mp4|m4v|webm|svg|svgz|eot|ttf|otf|woff|ico|webp|appcache|manifest|htc|crx|oex|xpi|safariextz|vcf)$" >
Header unset X-UA-Compatible
</FilesMatch>
</IfModule>
# ----------------------------------------------------------------------
# CORS-enabled images (#crossorigin)
# ----------------------------------------------------------------------
# Send CORS headers if browsers request them; enabled by default for images.
# developer.mozilla.org/en/CORS_Enabled_Image
# blog.chromium.org/2011/07/using-cross-domain-images-in-webgl-and.html
# hacks.mozilla.org/2011/11/using-cors-to-load-webgl-textures-from-cross-domain-images/
# wiki.mozilla.org/Security/Reviews/crossoriginAttribute
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
# mod_headers, y u no match by Content-Type?!
<FilesMatch "\.(gif|png|jpe?g|svg|svgz|ico|webp)$">
SetEnvIf Origin ":" IS_CORS
Header set Access-Control-Allow-Origin "*" env=IS_CORS
</FilesMatch>
</IfModule>
</IfModule>
# ----------------------------------------------------------------------
# Webfont access
# ----------------------------------------------------------------------
# Allow access from all domains for webfonts.
# Alternatively you could only whitelist your
# subdomains like "subdomain.example.com".
<IfModule mod_headers.c>
<FilesMatch "\.(ttf|ttc|otf|eot|woff|font.css)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
# ----------------------------------------------------------------------
# Proper MIME type for all files
# ----------------------------------------------------------------------
# JavaScript
# Normalize to standard type (it's sniffed in IE anyways)
# tools.ietf.org/html/rfc4329#section-7.2
AddType application/javascript js jsonp
AddType application/json json
# Audio
AddType audio/ogg oga ogg
AddType audio/mp4 m4a f4a f4b
# Video
AddType video/ogg ogv
AddType video/mp4 mp4 m4v f4v f4p
AddType video/webm webm
AddType video/x-flv flv
# SVG
# Required for svg webfonts on iPad
# twitter.com/FontSquirrel/status/14855840545
AddType image/svg+xml svg svgz
AddEncoding gzip svgz
# Webfonts
AddType application/vnd.ms-fontobject eot
AddType application/x-font-ttf ttf ttc
AddType font/opentype otf
AddType application/x-font-woff woff
# Assorted types
AddType image/x-icon ico
AddType image/webp webp
AddType text/cache-manifest appcache manifest
AddType text/x-component htc
AddType application/xml rss atom xml rdf
AddType application/x-chrome-extension crx
AddType application/x-opera-extension oex
AddType application/x-xpinstall xpi
AddType application/octet-stream safariextz
AddType application/x-web-app-manifest+json webapp
AddType text/x-vcard vcf
AddType application/x-shockwave-flash swf
AddType text/vtt vtt
# ----------------------------------------------------------------------
# Gzip compression
# ----------------------------------------------------------------------
<IfModule mod_deflate.c>
# Force deflate for mangled headers developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
</IfModule>
</IfModule>
# Compress all output labeled with one of the following MIME-types
<IfModule mod_filter.c>
AddOutputFilterByType DEFLATE application/atom+xml \
application/javascript \
application/json \
application/rss+xml \
application/vnd.ms-fontobject \
application/x-font-ttf \
application/xhtml+xml \
application/xml \
font/opentype \
image/svg+xml \
image/x-icon \
text/css \
text/html \
text/plain \
text/x-component \
text/xml
</IfModule>
</IfModule>
# ----------------------------------------------------------------------
# Expires headers (for better cache control)
# ----------------------------------------------------------------------
# These are pretty far-future expires headers.
# They assume you control versioning with filename-based cache busting
# Additionally, consider that outdated proxies may miscache
# www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/
# If you don't use filenames to version, lower the CSS and JS to something like
# "access plus 1 week".
<IfModule mod_expires.c>
ExpiresActive on
# Perhaps better to whitelist expires rules? Perhaps.
ExpiresDefault "access plus 1 month"
# cache.appcache needs re-requests in FF 3.6 (thanks Remy ~Introducing HTML5)
ExpiresByType text/cache-manifest "access plus 0 seconds"
# Your document html
ExpiresByType text/html "access plus 0 seconds"
# Data
ExpiresByType text/xml "access plus 0 seconds"
ExpiresByType application/xml "access plus 0 seconds"
ExpiresByType application/json "access plus 0 seconds"
# Feed
ExpiresByType application/rss+xml "access plus 1 hour"
ExpiresByType application/atom+xml "access plus 1 hour"
# Favicon (cannot be renamed)
ExpiresByType image/x-icon "access plus 1 week"
# Media: images, video, audio
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType video/ogg "access plus 1 month"
ExpiresByType audio/ogg "access plus 1 month"
ExpiresByType video/mp4 "access plus 1 month"
ExpiresByType video/webm "access plus 1 month"
# HTC files (css3pie)
ExpiresByType text/x-component "access plus 1 month"
# Webfonts
ExpiresByType application/x-font-ttf "access plus 1 month"
ExpiresByType font/opentype "access plus 1 month"
ExpiresByType application/x-font-woff "access plus 1 month"
ExpiresByType image/svg+xml "access plus 1 month"
ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
# CSS and JavaScript
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
</IfModule>
# ----------------------------------------------------------------------
# ETag removal
# ----------------------------------------------------------------------
# FileETag None is not enough for every server.
<IfModule mod_headers.c>
Header unset ETag
</IfModule>
# Since we're sending far-future expires, we don't need ETags for
# static content.
# developer.yahoo.com/performance/rules.html#etags
FileETag None
# ----------------------------------------------------------------------
# Start rewrite engine
# ----------------------------------------------------------------------
# Turning on the rewrite engine is necessary for the following rules and
# features. FollowSymLinks must be enabled for this to work.
# Some cloud hosting services require RewriteBase to be set: goo.gl/HOcPN
# If using the h5bp in a subdirectory, use `RewriteBase /foo` instead where
# 'foo' is your directory.
# If your web host doesn't allow the FollowSymlinks option, you may need to
# comment it out and use `Options +SymLinksIfOwnerMatch`, but be aware of the
# performance impact: goo.gl/Mluzd
<IfModule mod_rewrite.c>
Options +FollowSymlinks
# Options +SymLinksIfOwnerMatch
RewriteEngine On
# RewriteBase /
</IfModule>
# ----------------------------------------------------------------------
# Suppress or force the "www." at the beginning of URLs
# ----------------------------------------------------------------------
# The same content should never be available under two different URLs -
# especially not with and without "www." at the beginning, since this can cause
# SEO problems (duplicate content). That's why you should choose one of the
# alternatives and redirect the other one.
# By default option 1 (no "www.") is activated.
# no-www.org/faq.php?q=class_b
# If you'd prefer to use option 2, just comment out all option 1 lines
# and uncomment option 2.
# IMPORTANT: NEVER USE BOTH RULES AT THE SAME TIME!
# ----------------------------------------------------------------------
# Option 1:
# Rewrite "www.example.com -> example.com".
#<IfModule mod_rewrite.c>
# RewriteCond %{HTTPS} !=on
# RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
# RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
#</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
#RewriteCond %{HTTPS} off [OR]
#RewriteCond %{HTTP:X-Forwarded-SSL} off [OR]
#RewriteCond %{HTTP_HOST} ^www\.
#RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
#RewriteRule ^ https://%1%{REQUEST_URI} [NE, L, R]
#RewriteCond %{SERVER_PORT} ^80$
#RewriteRule ^(.*)$ https://%{SERVER_NAME} %{REQUEST_URI} [R=301,L]
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^ https://%1%{REQUEST_URI} [NE,L,R]
#RewriteCond %{HTTP_HOST} ^(^www\.)
#RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
#RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>
#<IfModule mod_rewrite.c>
# RewriteEngine On
# RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
# RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
# RewriteCond %{HTTPS} !=on
# RewriteCond %{SERVER_PORT} 80
# RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R,L]
#</IfModule>
# ----------------------------------------------------------------------
# Prevent 404 errors for non-existing redirected folders
# ----------------------------------------------------------------------
# without -MultiViews, Apache will give a 404 for a rewrite if a folder of the
# same name does not exist.
# webmasterworld.com/apache/3808792.htm
Options -MultiViews
# ----------------------------------------------------------------------
# Custom 404 page
# ----------------------------------------------------------------------
# You can add custom pages to handle 500 or 403 pretty easily, if you like.
# If you are hosting your site in subdirectory, adjust this accordingly
# e.g. ErrorDocument 404 /subdir/404.html
ErrorDocument 404 /404.html
# ----------------------------------------------------------------------
# UTF-8 encoding
# ----------------------------------------------------------------------
# Use UTF-8 encoding for anything served text/plain or text/html
AddDefaultCharset utf-8
# Force UTF-8 for a number of file formats
AddCharset utf-8 .atom .css .js .json .rss .vtt .xml
# ----------------------------------------------------------------------
# A little more security
# ----------------------------------------------------------------------
# To avoid displaying the exact version number of Apache being used, add the
# following to httpd.conf (it will not work in .htaccess):
# ServerTokens Prod
# "-Indexes" will have Apache block users from browsing folders without a
# default document Usually you should leave this activated, because you
# shouldn't allow everybody to surf through every folder on your server (which
# includes rather private places like CMS system folders).
<IfModule mod_autoindex.c>
Options -Indexes
</IfModule>
# Block access to "hidden" directories or files whose names begin with a
# period. This includes directories used by version control systems such as
# Subversion or Git.
<IfModule mod_rewrite.c>
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]
</IfModule>
# Block access to backup and source files. These files may be left by some
# text/html editors and pose a great security danger, when anyone can access
# them.
<FilesMatch "(\.(bak|config|sql|fla|psd|ini|log|sh|inc|swp|dist)|~)$">
Order allow,deny
Deny from all
Satisfy All
</FilesMatch>
# Increase cookie security
<IfModule php5_module>
php_value session.cookie_httponly true
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
#<IfModule mod_vhost_alias.c>
# RewriteBase /
#</IfModule>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ app.php [QSA,L]
</IfModule>
try this:
RewriteCond %{HTTPS} !^on [OR]
Rewritecond %{HTTP_HOST} !^example\.com
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]
To remove www and to enforce https you can use the following :
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^ https://%1%{REQUEST_URI} [NE,L,R]
Option 2, on apache 2.4 you can also use this :
RewriteEngine on
RewriteCond %{REQUEST_SCHEME}#%{HTTP_HOST} ^http#(?:www\.)?(.+)$
RewriteRule ^ https://%1%{REQUEST_URI} [NE,L,R]
Finally I had this working with following htaccess rules, as mentioned in my comment the rules posted in other answers were not working because of the elastic load balancer in place in my environment. All the HTTPS requests going through the ELB will have the value of X-FORWARDED-PROTO equal to “HTTPS“.
RewriteEngine on
RewriteCond %{HTTP_HOST} www.(.+) [OR,NC]
RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
RewriteRule ^/?(.*) http s://mydomain.com%{REQUEST_URI} [L,R=301]

CakePHP htaccess redirecting to live site when running site locally

I am working on a website which is using CakePHP. I need to start adding some features to this site so i pulled everything from the live site to my development machine(mac os lion with MAMP server). When i try to load up the site (localhost/example.com/), it automatically redirects me to the live site(www.example.com).
Here is the root htaccess file contents:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
RewriteRule ^$ webroot/ [L]
RewriteRule (.*) webroot/$1 [L]
</IfModule>
When i comment out the first two RewriteCond and first RewriteRule, my machine throws a 500 internal server error with no apache/php log output.
How can i run this website locally without automatically redirecting to the live site?
Is there any additional information i could provide?
edit: here is my document_root: /Applications/MAMP/htdocs. shouldn't it be /Applications/MAMP/htdocs/example.com?
edit: here is the /webroot/.htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule img/([0-9]*x[0-9]*)/(.*)/(.*)$ files/image/$2/$1/$3 [QSA,L]
RewriteRule (js|css)/vendors/(.*)$ vendors.php?type=$1&file=$2 [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>
AddType application/x-javascript .js
AddType text/css .css
<IfModule mod_deflate.c>
# compress content with type html, text, and css
AddOutputFilterByType DEFLATE text/css text/javascript application/javascript application/x-javascript text/js
SetOutputFilter DEFLATE
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
# Don't compress images/flash
SetEnvIfNoCase Request_URI \
\.(?:swf|flv)$ no-gzip dont-vary
# Don't compress images
# SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
# SetEnvIfNoCase Request_URI \/image\.php no-gzip dont-vary
# Also don't compress PDF and Flash-files 17-01-2004 MM
SetEnvIfNoCase Request_URI \.pdf$ no-gzip dont-vary
<IfModule mod_headers.c>
# properly handle requests coming from behind proxies
Header append Vary User-Agent
</IfModule>
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 10 years"
ExpiresByType text/js "access plus 10 years"
ExpiresByType text/javascript "access plus 10 years"
ExpiresByType application/x-javascript "access plus 10 years"
ExpiresByType application/javascript "access plus 10 years"
ExpiresByType image/png "access plus 10 years"
ExpiresByType image/gif "access plus 10 years"
ExpiresByType image/jpeg "access plus 10 years"
ExpiresByType video/x-flv "access plus 10 years"
</IfModule>
FileETag none
<IfModule mod_headers.c>
# 1 YEAR
<FilesMatch "\.(ico|pdf|flv)$">
Header set Cache-Control "max-age=29030400, public"
</FilesMatch>
# 1 WEEK
<FilesMatch "\.(jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=604800, public"
</FilesMatch>
# 2 DAYS
<FilesMatch "\.(xml|txt|css|js)$">
Header set Cache-Control "max-age=172800, proxy-revalidate"
</FilesMatch>
# 1 MIN
<FilesMatch "\.(html|htm|php)$">
Header set Cache-Control "max-age=60, private, proxy-revalidate"
</FilesMatch>
</IfModule>
edit: i've enabled debug logging level for apache so i can see more log messages. here is the log details upon visiting the root of the project with an error 500:
[Fri Jun 01 11:00:35 2012] [debug] mod_deflate.c(615): [client ::1] Zlib: Compressed 0 to 2 : URL /example.com/webroot/index.php
[Fri Jun 01 11:00:35 2012] [debug] mod_headers.c(756): headers: ap_headers_output_filter()
I've also included the access_log data after visiting the site with error 500:
127.0.0.1 - - [01/Jun/2012:11:03:02 -0400] "GET /example.com/ HTTP/1.1" 500 20 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.53 Safari/536.5"
Replace your existing .htaccess code with this:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /example.com/
RewriteRule (?!^webroot/)^(.*)$ webroot/$1 [L]
</IfModule>

Resources