How to name file and directory the same with .htaccess rewrite rules?

北战南征 提交于 2019-12-20 06:36:28

问题


I am trying to work on my "pretty-urls" and I'll be the first to admit I really don't know what I'm doing. I'm trying to wrap my head around it though. So what I am trying to do is have a file.php, but then also have a directory called file. That way I can go to www.example.com/file and it should pull up file.php. But I also want to be able to go to www.example.com/file/subfile and it should go to subfile.php IN the file directory.

Right now, I'm able to get rid of ".php" on all files and I've figured out how to "hide" the $_GET parameters in the URL, but this directory/file issue is throwing me for a loop. Any help is appreciated!

This is my current .htaccess

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^dire1/file/([0-9]+) dir1/file.php?id=$1 [NC,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^dir2/example/([0-9]+) dir2/example.php?id=$1 [NC,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.php [L,QSA]

回答1:


This is because of mod-dir Apache directory module that runs before mod-rewrite . When you request an existent directory without a traling slash the mod-dir issues a permanent 301 Redirect from /dir to /dir/ and that is why you are unable to rewrite the uri.

To fix this, you need to tell mod-dir not to perform the redirection when a directory without a traling slash is requested. You can use DirectorySlash directive in your htaccess to change this behaviour.

Add the following line to your htaccess :

DirectorySlash off

Reference : https://httpd.apache.org/docs/2.4/mod/mod_dir.html




回答2:


Have it this way:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^dire1/file/([0-9]+) dir1/file.php?id=$1 [NC,QSA,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^dir2/example/([0-9]+) dir2/example.php?id=$1 [NC,QSA,L]

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

Last rule will serve /file.php when URI is example.com/file/

Note that if you serve example.com/file (no trailing slash) then Apache's mod_dir module will add a trailing slash in the end to make it example.com/file/ and then server /file.php.

Turning off this trailing slash behavior is considered a security risk and it may expose your internal directory structure to your visitors.



来源:https://stackoverflow.com/questions/51679072/how-to-name-file-and-directory-the-same-with-htaccess-rewrite-rules

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