skip to Main Content

my problem is that in root directory I have this rewrite rule in my .htaccess file

RewriteRule main-page /index.php

and it works when I go to the root directory in browser.
But when I visit page.com/panel/main-page it also redirects to the index.php in root directory.

2

Answers


  1. Good question.
    That line is correct:

    RewriteRule main-page /index.php
    

    But in that case, we’ve got if URL contains main-page it always be redirected to the /index.php.

    In pure apache2 configuration, below lines always do what you want:

    RewriteEngine On 
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^main-page /index.php
    RewriteRule ^(*.)/main-page $1/index.php
    
    Login or Signup to reply.
  2. You need to be more precise in your matching pattern. Your current matching pattern main-page will match any path in this list of examples, which is not what you actually want:

    • /main-page
    • /folder/main-page
    • /folder/main-page/whatever
    • /some-other-main-page
    • /some-other-main-page-in-green

    Instead you want to be precise and only match the literal string “main-page” as absolute path and nothing else:

    RewriteEngine on
    RewriteRule ^/?main-page$ /index.php [END]
    

    In case you receive an internal server error (http status 500) using the rule above then chances are that you operate a very old version of the apache http server. You will see a definite hint to an unsupported [END] flag in your http servers error log file in that case. You can either try to upgrade or use the older [L] flag, it probably will work the same in this situation, though that depends a bit on your setup.

    This implementation will work likewise in the http servers host configuration or inside a distributed 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 distributed 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 distributed configuration files (“.htaccess”). Those distributed 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).

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