简体   繁体   中英

How to apply mod_rewrite rules to files within directory?

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?

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:

在此处输入图片说明

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM