How do I create an .htaccess to serve index if the last node is a directory, else, serve a file?

StackOverflow https://stackoverflow.com/questions/17242643

  •  01-06-2022
  •  | 
  •  

문제

So, if I have the following URL:

http://www.example.com/Foo/Bar/Drink/

The last node of the URL (in this case, Drink) will be either a directory, in which case I want to serve index.php, or it will be a file named "Drink.php", in which case I want to serve them that file.

http://www.example.com/ would obviously serve index.php.

Both would maintain that "pretty URL" look with the trailing slash.

Is this possible? The site will follow this format consistently and I'm really trying to avoid having to route everything through the main index file.

도움이 되었습니까?

해결책

place this code in .htaccess under the root directory of your site

Options -MultiViews
RewriteEngine ON    

RewriteCond %{REQUEST_FILENAME} -d
RewriteRule (.+) /$1/index.php [QSA,L]

RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ /$1.php [QSA,L]

다른 팁

I think a rewrite rule might do the trick. Try something like this:

Options +FollowSymLinks
DirectoryIndex index.php

RewriteEngine On
RewriteBase /Foo/Bar/Drink
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /Foo/Bar/Drink HTTP/
RewriteRule ^Drink.php$ http://www.yourdomain.com/Foo/Bar/Drink [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /Foo/Bar/Drink/Drink.php [L]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top