htacess redirect is not redirecting - reactjs

I'm using create-react-app together with react-router. How can I make any of the following variations (I don't think I missed any):
www.example.com
example.com
http://example.com
http://www.example.com
redirect to:
https://example.com (notice the https secured, and no www.)
I created an .htaccess file with the following code:
<ifModule mod_rewrite.c>
Options +FollowSymLinks
IndexIgnore */*
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*) https://%{HTTP_HOST}/$1 [R,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !\/$
RewriteRule ^(.*) /
</ifModule>
<IfModule mod_headers.c>
<FilesMatch "sw\.js$">
Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform"
Header set Pragma "no-cache"
</FilesMatch>
</IfModule>
When I add that, the routes get directed to secured https, but the www is there when I type it in the url. How can I have the browser always redirect to not have www.?

The rediretion to another host should work better like that, note the hard wired target host name:
RewriteEngone on
RewriteCond %{HTTPS} off
RewriteRule ^/?(.*)$ https://example.com/$1 [R=301]
RewriteCond %{HTTP_HOST} !^example\.com$
RewriteRule ^/?(.*)$ https://example.com/$1 [R=301]
It is a good idea to start out with a 302 temporary redirection and only change that to a 301 permanent redirection later, once you are certain everything is correctly set up. That prevents caching issues while trying things out...
Place those rules before any internal rewriting rules (your example shows a general rewriting to ?/).
This implementation will work likewise in the http servers host configuration or inside a dynamic configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a dynamic configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.
And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those dynamic configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).

Related

Error 403 forbidden when using React Router with Apache

When I deploy my website built with React and React-router the landing page of my website works fine but when I try to navigate into my website I run into 403 forbidden response. I use Apache as an HTTP server and the general config of my server is the following :
<IfModule mod_php.c>
php_value date.timezone Europe/Brussels
</IfModule>
<IfModule mod_userdir.c>
UserDir /var/www/users/staff/*
</IfModule>
For your information, the website is located under /var/www/projects
I added the following .htaccess to my project :
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
</IfModule>
Despite those configurations the 403 forbidden error when navigating in pages managed by react-router. Did I miss some configurations?
It seems that the settings you have applied are not enough, You should change some parameters in apache.conf too...
open the apache main config file, Its path varies depending on your distribution, that's located in one of these locations:
1- /etc/apache2/httpd.conf
2- /etc/apache2/apache2.conf
3- /etc/httpd/httpd.conf
4- /etc/httpd/conf/httpd.conf
look for "AllowOverride" parameter like the example below:
<Directory "/var/www/blahblah">
AllowOverride All
</Directory>
And give the "All" value to that.
Then create a .htaccess file in the root folder of the webserver & set the following configs:
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
NOTE: Before performing these things you have to enable the rewrite module, By entering the following commands you can do this:
debian base: sudo a2enmod rewrite
centos: uncomment mod_rewrite.so in /etc/httpd/conf/httpd.conf
Finally, restart your web server... Now expected there is no anymore problem.
If you got any permission/server error take a look at the webserver logs which are located in one of these locations:
1- /var/log/httpd/
2- /var/log/apache2

LetsEncrypt and CakePhp issue

I'm trying to install LetsEncrypt with cakephp and I'm having some issues.Let me describe:
First I'm installing LetsEncrypt on a server with CentOS 6.
As mentioned on several websites it needs a python upgrade from 2.6 to 2.7 as LetsEncrypt needs Python 2.7. Which I did.
Then if I run ./letsencrypt-auto I get
"No installers are available on your OS yet; try running "letsencrypt-auto certonly" to get a cert you can install manually"
I understand that this is normal as there is no installer for CentOS 6.
So I run ./letsencrypt-auto certonly.A window appears.I have the choice between:
Place files in webroot directory
Automatically use a temporary webserver
So I press 1.Then I enter my domain name.And I see:
Enter a new webroot
I press ok and I see my root directory.I select /root
And then I have the following error:
Failed authorization procedure. www.example.com (http-01): urn:acme:error:unauthorized :: The client lacks sufficient
authorization :: Invalid response from
http://www.example.com/.well-known/acme-challenge/-CnpDIgxBB9EOH-BCssGOyiunFjnMlGLWhWw9roE4Ds:
"
500 Internal Server Error Inter"
IMPORTANT NOTES:
- The following errors were reported by the server:
Domain: www.example.com Type: unauthorized Detail: Invalid
response from http://www.example.com/.well-known
/acme-challenge/-CnpDIgxBB9EOH-BCssGOyiunFjnMlGLWhWw9roE4Ds:
"
500 Internal Server Error
Inter"
To fix these errors, please make sure that your domain name was
entered correctly and the DNS A record(s) for that domain
contain(s) the right IP address.
And here comes cakephp. As mentioned I'm using cakephp. And it seems that for this specific issue you need to modify htaccess files as mentioned here
I need to add "RewriteRule ^(\.well-known/.*)$ $1 [L]" as the first rewrite rule in the root htaccess and the app/.htaccess
Which I did.
root .htaccess:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^(\.well-known/.*)$ $1 [L]
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]
AddDefaultCharset UTF-8
</IfModule>
app/.htaccess:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^(\.well-known/.*)$ $1 [L]
RewriteRule ^$ webroot/ [L]
RewriteRule (.*) webroot/$1 [L]
AddDefaultCharset UTF-8
</IfModule>
But I still have the same problem
Any idea what I did wrong?
Thanks a lot
Cake's webroot has an .htaccess with a RewriteCond %{REQUEST_FILENAME} !-d rule that means cake will not be called in for any request that matches an actual directory inside webroot.
So just place the .well-known directory and everything else that is needed inside the webroot directory, you should be able to access them fine without messing up with .htaccess.
PS. In some cases the file Let's encrypt requires is not served back as text, in which case you should enable the headers apache module (if not enabled already) and put the following rule in your apache or virtualhost config:
<IfModule mod_headers.c>
<LocationMatch "/.well-known/acme-challenge/*">
Header set Content-Type "text/plain"
</LocationMatch>
</IfModule>

How to benefit of prerender.io services if my Apache server doesn't allow a proxy

Having an Angular app, I want to benefit of an HTML prerendering for Search engines bots.
Here's my .htaccess configuration:
<IfModule mod_headers.c>
RequestHeader set X-Prerender-Token "My_Token"
</IfModule>
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine on
<IfModule mod_proxy_http.c>
RewriteCond %{HTTP_USER_AGENT} baiduspider|facebookexternalhit|twitterbot|rogerbot|linkedinbot|embedly|quora\ link\ preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator [NC,OR]
RewriteCond %{QUERY_STRING} _escaped_fragment_
# Only proxy the request to Prerender if it's a request for HTML
RewriteRule ^(?!.*?(\.js|\.css|\.xml|\.less|\.png|\.jpg|\.jpeg|\.gif|\.pdf|\.doc|\.txt|\.ico|\.rss|\.zip|\.mp3|\.rar|\.exe|\.wmv|\.doc|\.avi|\.ppt|\.mpg|\.mpeg|\.tif|\.wav|\.mov|\.psd|\.ai|\.xls|\.mp4|\.m4a|\.swf|\.dat|\.dmg|\.iso|\.flv|\.m4v|\.torrent|\.ttf|\.woff))(.*) http://service.prerender.io/http://example.com/$2 [P,L]
</IfModule>
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]
</IfModule>
My issue is that the P flag involving proxy causes a 403 error:
"You don't have permission to access /"
when I run the following command:
curl http://example.com?_escaped_fragment_=
I don't own a dedicated server but an external shared Apache server.
I contacted the support of this server instance and they argue that proxy are forbidden on shared instances, resulting in an error 403.
Is there any workaround to to benefit of prerender.io with Apache and .htaccess configuration without switching to a dedicated Apache Server?
Is the proxy flag mandatory?
The proxy flag is mandatory because a redirect would incorrectly tell the crawlers to send your users to the redirected site instead.

Configuring Apache to rewrite urls to index.html in root directory

My AngularJS application is using html5 mode for pretty urls. The urls on my local environment work but typing full urls directly into the browser causes my test server (set up on Heroku) to respond with 404 "Not Found" errors.
Examples:
1) Typing "localhost/log_in" or "localhost" directly into the browser results the login page.
2) Typing "localhost/fkjdlfdsaf" or any other url that begins with "localhost/" directly into my browser results in the login page.
3) Typing "myapplication.herokuapp.com" (test environment) directly into the browser also results in the login page.
4) Typing "myapplication.herokuapp.com/log_in" (test environment), however, incorrectly results in a 404 "Not Found" error.
It seems like the test environment server hasn't loaded [root dir]/index.html since the file contains scripts (including a route that serves the "login" page if the url doesn't match any other routes).
Can somebody tell me what I'm missing on my test server? I prefer solutions that modify the "httpd.conf" file over using a .htaccess file.
Snippet from httpd.conf on local server:
DocumentRoot "C:/Sites/myApplication"
<Directory "C:/Sites/myApplication">
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Require all granted
RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]
</Directory>
To configure web servers on Heroku, I created two files, procfile.txt (see this and this) as well as apache_app.conf (see this).
procfile.txt (heroku):
web: vendor/bin/heroku-php-apache2 -C apache_app.conf
apache_app.conf:
RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]

Can .htaccess help me in this situation?

If a user goes to URL, say: http://www.domain.com/image/orange.jpg
but orange.jpg does not exist, however orange.png does, can .htaccess allow the user to find it?
That should be possible. mod_rewrite allows to check for the existance of files. And it allows multiple passes of rewriting in case you do not stop that process actively using the [L] flag. .
So have a try with something like this as a starting point (untested):
RewriteEngine on
RewriteCond %{REQUEST_URI} ^/image/([^/.]).jpg$
RewriteCond %{REQUEST_URI} !-f
RewriteRule ^/image/([^/.]).jpg /image/$1.png
RewriteCond %{REQUEST_URI} ^/image/([^/.]).png$
RewriteCond %{REQUEST_URI} !-f
RewriteRule - /image/no-found [G,L]
The above applies if defined inside the central server configuration (per-host configuration). For .htaccess style files the syntax is slightly different: the leading slash (/) inside the RewriteRule must not be present in that case. If you have a choice do the rewriting in the server configuration. .htaccess style files are something like a workaround and very error prone. Try to avoid them if possible.
Note however that such setup is somewhat limited and annoying to maintain. Often it is a better alternative to setup a small wrapper script (probably php based) that processes the request and check a number of alternatives before deciding what response to send. You could rewrite requests to something like this:
RewriteEngine on
RewriteRule ^/image/([^/.])\..+$ /image.php?name=%1
Now you can serve that request with a script image.php where you can check for existing versions of images without haste and return headers and content to your liking.

Resources