I want users to only be able to access domain.com or domain.com/. Anything afterwards, even domain.com/index.php, should redirect to domain.com.
I have this .htaccess
RewriteBase /
RewriteEngine On
Options -Indexes
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTPS} =on
RewriteRule ^$ index.php [L]
RewriteCond %{HTTPS} =on
RewriteRule ^([^/]+)$ 404.php?cp=$1 [L,QSA]
The problem is that the parameter is never empty. Therefore 404.php is always called. If I go to domain.com, it redirects to 404.php?cp=index.php
. If I remove the index.php rule, it redirects to 404.php?cp=index.php
. If I delete the index.php file and rule, I get a server error. If I allow index.php
, then it works and redirects to index.php but that’s not what I want. Users shouldn’t be able to call index.php, or any file, or add anything after the domain even if index.php is ultimately called. So basically I want to allow an internal redirect to index.php only if it was instructed by the htaccess file, not by the user.
How can I fix this?
2
Answers
The following redirect will redirect any request that is not
/
to/
. domain.com and domain.com/ are the same thing.To present
index.php
for request tohttp://example.com
you don’t need a rewrite rule, just useDirectoryIndex
directive like this:Now to rewrite to
404.php
if users enter anything afterexample.com/
you can checkTHE_REQUEST
based condition.THE_REQUEST
variable represents original request received by Apache from your browser and it doesn’t get overwritten after execution of other rewrite directives. Example value of this variable isGET /index.php?id=123 HTTP/1.1
So combining it all, your full suggested .htaccess should look like this:
However do keep in mind that last rule will also redirect any request for resources such as images, stylesheets and js files to
https://example.com