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