Rewrite URL: remove subfolders and file extension from URL

I am trying to remove the .php file extension and the && & subfolder from the 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

Conclusion:

127.0.0.1/project/beta

Here is what I got so far:

Removing just the extension works fine, the problem with deleting 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 advise Thank you.

+4
source share
3 answers

You can have this .htaccess inside the directory /project/:

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]
+3
source

You can use the following regular expression to capture the required fields from a URL. Then use the obtained values ​​1, 2 to generate the output.

([0-9]*\.[0-9]*\.[0-9]*\.[0-9]*\/[A-Za-z0-9]*).*(\/.*)\.php

. 1 2.

. ipv4

+1

- RewriteRule.

:

Apache , /project/beta /project/folder/subfolder/beta.php, /project/alfa /project/folder/alfa.php?

:

RewriteRule ^project/beta/? /project/folder/subfolder/beta.php [QSA,L]

RewriteRule ^/project/alfa/? /project/folder/alfa.php [QSA,L]

, - , , script. - :

, script. script , /project php, URL ( alfa/beta). , .

0
source

Source: https://habr.com/ru/post/1683806/


All Articles