.htaccess Rewrite Within Directory - Hide PHP extension and force trailing slash

回眸只為那壹抹淺笑 提交于 2020-01-03 02:56:08

问题


I'm trying to hide the .php extension from my files as well as force a trailing slash on the resulting URLs.

Example: A request to /about.php would become /about/ and requests to /about would go to /about/.

The following rewrite code worked perfectly when I was in the root of my hostdomain:

RewriteEngine On
RewriteRule ^(.*)/$ /$1.php [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://edit.mydomain.org/$1/ [R=301,L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)\.php\ HTTP/ [NC]
RewriteRule .+ http://edit.mydomain.org/%1  [R=301,QSA]

However, I need to move my files into a directory of this host name. Adding a directory name to the rules and having the .htaccess in the directory itself didn't work at all and seems to cause a endless redirect.

I looked around StackOverflow and other websites and tried numerous examples and ended up with many different errors with the most common being:

  • Everything is an endless redirect.
  • Everything except the directory home page is a 500 Error.
  • about.php redirects to /about but there's no redirect to /about/ and /about/ displays a 500 Error.
  • Everything working, but the home page (of the directory) index.php when accessed without a filename goes into an endless redirect.
  • Things redirect to edit.mydomain.org/home/username/public_html/mydomain.org/edit/pagename.php which obviously doesn't exist.

Thanks for any help! I really need to keep these files in a directory although the .htaccess could go into the host name root if its needed.

The directory for this would be edit.mydomain.org/dave/


回答1:


Save this as a .htaccess and put it in the 'dave' directory

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\..+$
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^(.*)$ http://edit.mydomain.org/dave/$1/ [R=301,L]

RewriteRule ^(.*)/$ $1.php [L]



回答2:


This works for me

RewriteBase /
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html


来源:https://stackoverflow.com/questions/5527789/htaccess-rewrite-within-directory-hide-php-extension-and-force-trailing-slash

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