memrat
memrat

Reputation: 167

Edit existing .htaccess to work with subdirectories too

I have an existing .htaccess file that looks like this:

Options -Indexes
RewriteEngine On
RewriteBase /
RewriteRule ^posts/(.*)/(.*).html$ index.php?content=blog&postid=$1&kwd=$2
RewriteRule ^aposts/(.*)/(.*).html$ index.php?content=autopost&postid=$1&kwd=$2
RewriteRule ^category/(.*)/(.*).html$ index.php?content=category&cat=$1&otext=$2
RewriteRule ^content/(.*).html$ index.php?content=$1
RewriteRule ^searching/(.*).html$ index.php?content=search&k=$1
RewriteRule ^related/(.*).html$ index.php?content=related&k=$1
RewriteRule ^blog/(.*)/(.*).html$ index.php?content=blog&postid=$1&kwd=$2
RewriteRule ^posts$ index.php?content=blog
RewriteRule ^sitemap\.xml$ sitemap.php [L]
RewriteRule ^robots\.txt$ robots.php [L]
ErrorDocument 404 /404.php

This works how it was initailly intended for root domain address visitors.

What I want now is to add the functionality of accepting directories too, for example:

example.com/directory1

or

example.com/dir1/dir2/dir3/dir4

but I want it to keep the same functionality as it currently does.

I hope that makes sense, but feel free to ask for clarification.

Thanks for anyhelp with this.

Upvotes: 1

Views: 106

Answers (1)

isogram
isogram

Reputation: 318

RewriteRule ^posts/(.*)/(.*).html$ index.php?content=blog&postid=$1&kwd=$2

This rule of yours always only matches when the URI starts with "posts".

To allow one or more subdirectories before such a rule, you want to look for one or more characters followed by a / before "posts":

(.+/)? this selects "one or more of any characters, followed by a /", zero or one times. Since "any character" also includes a slash this counts for any amount of subdirectories, as long as after the last slash the "posts" appears.

Since an extra set of parentheses is introduced, you will need to access $2 and $3 now.

So your rule becomes:

RewriteRule ^(.+/)?posts/(.*)/(.*).html$ index.php?content=blog&postid=$2&kwd=$3

You can apply this to each of your rules.

Upvotes: 1

Related Questions