简体   繁体   中英

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

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.

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]*)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM