skip to Main Content

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


  1. The following redirect will redirect any request that is not / to /. domain.com and domain.com/ are the same thing.

    RewriteEngine on
    RewriteCond %{REQUEST_URI} !^/$ 
    RewriteRule . / [R=301,L]
    
    Login or Signup to reply.
  2. 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?

    To present index.php for request to http://example.com you don’t need a rewrite rule, just use DirectoryIndex directive like this:

    DirectoryIndex index.php
    

    Now to rewrite to 404.php if users enter anything after example.com/ you can check THE_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 is GET /index.php?id=123 HTTP/1.1

    So combining it all, your full suggested .htaccess should look like this:

    DirectoryIndex index.php
    Options -Indexes
    
    RewriteEngine On
    
    # http -> https redirection (note there is no REQUEST_URI)
    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://%{HTTP_HOST} [L,R=301]
    
    # redirect anything after example.com/ to example.com
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,}s/+[^s?]
    RewriteRule . / [L,R=301]
    

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search