skip to Main Content

I’m trying to apply rewrite conditions in my htaccess file to all pages contained within a specific directory on my website, but not the directory index itself.

Ultimately, I’m trying to remove .php file extension from pages within a specific directory.

What I currently have now:

https://www.example.com/directory/page-1.php

End result I’m trying to achieve:

https://www.example.com/directory/page-1

Additionally, if a user attempts to visit the .php version of the page, it 301 redirects to the new version without the .php file extension.

Example matches:

https://www.example.com/directory/page-1.php
https://www.example.com/directory/page-2.php

Should not match:

https://www.example.com/directory/

Here’s what I have so far:

RewriteCond %{REQUEST_URI} /directory/[^s]+$

How should the RewriteRule be written?

2

Answers


  1. The expression that might help us to find a RewriteRule can look like:

    ^https?://(www.)?example.com/directory/[^s]+.php$
    

    which would fail our undesired URLs, and pass the desired ones.

    Demo

    Our RewriteRule might likely look like:

    <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteCond %{REQUEST_URI} (.*/directory/)([^s]+).php [NC]
        RewriteRule (.*directory/)([^s]+).php   $1$2 [L,R=301]
    </IfModule>
    

    Demo

    RewriteRule Test

    You can test your RewriteRules in htaccess.madewithlove.be.

    RegEx Circuit

    jex.im visualizes regular expressions:

    enter image description here

    We might also want to clear our browser cache, every time that we would change our htaccess file.

    Login or Signup to reply.
  2. You can use the following rule in htaccess in your subfolder create one if it doesn’t already exist :

     RewriteEngine on
     #rule for /subfolder/htaccess 
    #redirect /subfolder/file.php to /file
    #The condition bellow prevents infinite loop/Too many redirects  error
    RewriteCond %{ENV_REDIRECT_STATUS} ^$
    RewriteRule ^(.+).php$ /subfolder/$1 [L,R]
    #internally map /subfolder/file to /subfolder/file.php
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^(.+)/?$ /subfolder/$1.php [L]
    

    If you want to use your root htaccess file instead , then add the following contents:

     RewriteEngine on
     #rule for root/.htaccess 
    #redirect /subfolder/file.php to /file
    #The condition bellow prevents infinite loop/Too many redirects  error
    RewriteCond %{ENV_REDIRECT_STATUS} ^$
    RewriteRule ^subfolder/(.+).php$ /subfolder/$1 [L,R]
    #internally map /subfolder/file to /subfolder/file.php
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^subfolder/(.+)/?$ /subfolder/$1.php [L]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search