Modify url with .htaccess file

2019-09-16 02:39发布

问题:

I would like to delete extensions like .php, .html, etc from my url and this is what I use:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
RewriteRule ^([^\.]+)$ $1.html [NC,L]

It works but I don't know if this is the best way to do this and I also don't understand how it works, could someone explain it?

The second thing I would like to realise is to make the URL more beautiful by doing something like this:

this is my URL: http://domain.com/portfolio/project.php?id=1 this is what I would like to see: http://domain.com/portfolio/project/1

Thanks in advance

回答1:

You can use these rules in site root .htaccess:

RewriteEngine On

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

# rewrite /portfolio/project to /portfolio/project.php
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

# rewrite /portfolio/file to /portfolio/file.html
RewriteCond %{DOCUMENT_ROOT}/$1\.html -f
RewriteRule ^(.+?)/?$ $1.html [L]