.htaccess remove all .php and id as default parameter after slash

对着背影说爱祢 提交于 2019-12-24 06:08:11

问题


I have the following .htaccess file which helps me to rewrite the http://domain/path/project.php?id=1 as http://domain/path/project/1.

RewriteBase /
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*)$ project.php?id=$1 [QSA,NC,L]

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

RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^(.*)$ project.php [QSA,NC,L]   

But I need all the php's in the current directory to be replaced in the same way. I have edit_project.php?id=1, delete_project.php?id=1 etc. id is a default parameter for all the php's except some. So I want the htaccess to do the following.

http://domain/path/*.php?id=1 as http://domain/path/*/id and when there is no id, it should just look like http://domain/path/* and when there are other parameters, it should look like http://domain/path/*?param=value

Since I am new to .htaccess, any help would be appreciated. Also please explain me how this works.


回答1:


You can use the following :

RewriteEngine On
RewriteBase /    
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^path/([^/]+)/?([0-9]*)/?$ $1.php?id=$2 [QSA,NC,L]

This will rewrite /path/file/id to /file.php?id=id

Since $1 represents match of first group of ([^/]+) and $2 represents match of second group of ([0-9]*)




回答2:


You can use these rules in your root .htaccess:

RewriteEngine On

# redirect /path/file.php?id=123 to /path/file/123
RewriteCond %{THE_REQUEST} /(path/.+)\.php\?id=([^\s&]+) [NC]
RewriteRule ^ /%1/%2? [R=302,L,NE]

# hide .php extension 
RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=302,NE,L]

# rewrite /path/file/123 to /path/file.php?id=123
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
RewriteRule ^(path/[^/]+)/([^/]+)/?$ $1.php?id=$2 [QSA,NC,L]

# hide .php extension 
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
RewriteRule ^(path/[^/]+)/?$ $1.php [NC,L]

Make sure there is no .htaccess in /path/ directory.



来源:https://stackoverflow.com/questions/37709821/htaccess-remove-all-php-and-id-as-default-parameter-after-slash

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