Rewrite URL : remove sub folders and file extension from URL

匿名 (未验证) 提交于 2019-12-03 01:22:02

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!