Boris Bär
Boris Bär

Reputation: 99

Get .htaccess to show .index.php

I'm trying to make my .htaccess file show the index.php of a subfolder without having it displayed in the URL bar but I'm a noob with .htaccess.

This is what I want ...

Full Path: http://example.com/pages/games/demons-souls/index.php

URL Path: http://example.com/games/demons-souls/

So far I've managed to get it to show http://example.com/games/demons-souls/index

Strange enough it works when I don't hide the pages subdirectory in the URL, e.g.

http://example.com/pages/games/demons-souls/

My .htaccess file looks like this ...

Options +MultiViews

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# H I D E - P H P - E X T E N S I O N

RewriteRule ^([^/]+)/$ $1.php
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php

# H I D E - F O L D E R : P A G E S

RewriteCond %{REQUEST_URI} !^pages/games
RewriteRule ^games/(.*)$ pages/games/$1 [L]

# R E D I R E C T - I N D E X - ? ? ?

I'd really appreciate some help!

Upvotes: 1

Views: 85

Answers (1)

MrWhite
MrWhite

Reputation: 45829

Your directives are in the wrong order. Your second rule is unconditional (RewriteCond directives only apply to the first RewriteRule directive that follows). However, if you are enforcing a trailing slash on your URLs then presumably these don't map to files anyway? Although you have enabled MultiViews, which is essentially making your directives that handle extensionless URLs redundant.

The REQUEST_URI server variable always starts with a slash so your condition (that checks against !^pages/games - no slash prefix) will always be successful.

Try the following instead:

Options -MultiViews

RewriteEngine On

# Rewrite "/games/<anything>" to "/pages/games/<anything>"
RewriteCond %{REQUEST_URI} !^/pages/games
RewriteRule ^games($|/.*) pages/$0 [L]

# This may not be required...
# Rewrite extensionless URLs to ".php" if they exist
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+)/$ $1.php [L]

The above will internally rewrite a request for /games/demons-souls/ to /pages/games/demons-souls/. mod_dir will then issue an internal subrequest for index.php (the DirectoryIndex document) - there is nothing extra you need to add for this to work.

In the example you've given you don't actually need the second rule that handles extensionless URLs. (?) Note that your directive implies that your extensionless URLs all end in a trailing slash. For example, /games/demon-souls/foo/ would be internally rewritten to /pages/games/demon-souls/foo.php if that file exists.

Strange enough it works when I don’t hide the pages subdirectory in the URL, e.g.

http://example.com/pages/games/demons-souls/

In that scenario you aren't using your .htaccess directives at all. When you request a physical directory then mod_dir searches for the DirectoryIndex document (ie. index.php) in that directory and serves it if found.

Upvotes: 1

Related Questions