问题
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