skip to Main Content

I’ve moved many url in my site from: /folder/page.php to: /folder/page/.

Now I want to redirect old url to new url, so I added in my .htaccess this rule:

RedirectMatch permanent /folder/(.*).php https://www.site.it/folder/$1/

But it doesn’t work, this rule first redirect to /folder/page/ and then redirect again to /folder/page/index/

So I tried this:

RedirectMatch permanent /folder/(?!index).php https://www.site.it/folder/$1/

But it works like the above rule.

I tested also:

RedirectMatch permanent /folder/(?!index)(.*).php https://www.site.it/folder/$1/

same again.

I use .htaccess only in the root folder, here is the content before the new rule:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

These rules are required to redirect http traffic to https and are suggested by the web hosting service I use.

I also tested wrong RedirectMatch rule without any other.

How can I redirect all page except index.php?

Here is the list of url and the desired behavior:

/folder/                      not match     no action
/folder/index.php             not match     no action
/folder/subfolder/            not match     no action
/folder/subfolder/index.php   not match     no action
/folder/anindex.php           match         redirect to /folder/anindex/
/folder/indexfile.php         match         redirect to /folder/indexfile/
/folder/anindexfile.php       match         redirect to /folder/anindexfile/
/folder/anotherfile.php       match         redirect to /folder/anotherfile/

Please do not suggest to use mod_rewrite because it is not the best practice as described here.

2

Answers


  1. Chosen as BEST ANSWER

    I found this question: Match everything except for specified strings that help me to fix regex.

    RedirectMatch permanent /folder/(?!.*(index))(.*).php https://www.site.it/folder/$2/
    

    This rule match everything except index so redirect /folder/page.php only once to /folder/page/ but unfortunately, as @anubhava pointed out, this rule doesn't match any page name that contains index.

    After further dig, I found this solution:

    RedirectMatch permanent /folder/(?!index.php$|$)(([w-]+).php$) https://www.site.it/folder/$2/
    

    Anyway thanks to @anubhava that support me.


  2. You may add a new rule below your existing rule:

    RewriteCond %{THE_REQUEST} s(/folder/[w-]+).php[?s] [NC]
    RewriteRule ^ %1/ [L,R=301]
    

    THE_REQUEST matches only original URI sent by client, it won’t match modified REQUEST_URI.

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