可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am trying to remove .php file extension and folder && subfolder from URL if they exist.
Case 1
Input:
127.0.0.1/project/folder/alfa.php
output:
127.0.0.1/project/alfa
Case 2
Input:
127.0.0.1/project/folder/subfolder/beta.php
Output:
127.0.0.1/project/beta
Here is what I have got so far :
Removing just extension works fine, having problem with removing folders
# Turn mod_rewrite on RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^((?! folder/).+?)/?$ folder/ [L,NC] RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [QSA,L]
Please advice Thanks.
回答1:
You can have this .htaccess inside /project/
directory:
RewriteEngine On RewriteBase /project/ # rewrite to folder/subfolder/ RewriteCond %{DOCUMENT_ROOT}/project/folder/subfolder/$1.php -f RewriteRule ^(.+?)/?$ folder/subfolder/$1.php [L] # rewrite to folder/ RewriteCond %{DOCUMENT_ROOT}/project/folder/$1.php -f RewriteRule ^(.+?)/?$ folder/$1.php [L]
回答2:
You can use the following regex to capture the required fields from URL. Then use captured values 1, 2 to generate the output.
([0-9]*\.[0-9]*\.[0-9]*\.[0-9]*\/[A-Za-z0-9]*).*(\/.*)\.php
You can see the demo here. It captures the address and parent folder in 1 and filename in 2.
Note : I have considered the address to be ipv4
回答3:
Based on your clarification in your comment on your question - this will be hard to handle dynamically via RewriteRule
alone.
Consider this:
How is Apache to know that /project/beta
maps to /project/folder/subfolder/beta.php
while /project/alfa
maps to /project/folder/alfa.php
?
You could hardcode these like so:
RewriteRule ^project/beta/? /project/folder/subfolder/beta.php [QSA,L]
RewriteRule ^/project/alfa/? /project/folder/alfa.php [QSA,L]
If this isn't feasible due to a large number of rules that would be required here I would attempt to solve this via a script. Something like this:
If the requested resource is not a file or directory send it to a script. Then have the script search a target directory structure such as /project
for all php files that match the second portion of your masked URL (the alfa / beta part). If only one file is found require it in order to run it.