简体   繁体   中英

Some Pages without .php extension Mod Rewrite

So I have this site, It has a directory structure like this:

  1. index.php
  2. page1.php
  3. page3.php
  4. folder/index.php
  5. example/index.php
  6. page4.php

I want to remove the .php file extension only from the URLs that are not in a subdirectory. Because If I remove the .php from all the URLS like so:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L] 

The files in subdirectories like which were previously accessible by this URL: https://example.com/folder now give a 404 unless I enter index.php or file name at the end of it.

So I want to know the following:

  • How can I remove .php from only a select few targeted files so that the files in a folder/subdirectory are not affected?
  • How can I change the above .htaccess code so that it does not target the files that are in a folder/subdirectory?

If you want to add .php extension to only files in site root then use:

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^/.]+)/?$ $1.php [L]

Here negated character class [^/.]+ will match only file in current directory as it matches 1 or more characters that are not / and .

However if you want to correctly add .php to all files then use this rule:

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $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