TimNguyenBSM
TimNguyenBSM

Reputation: 827

Apache URL Rewrite: Dealing with Two Similar Rules

Question:

How do I write rules when they are similar?

My Rules:

RewriteRule ^blog/([0-9]+)/[-0-9a-zA-Z]+/?$ index.php?action=blog&postID=$1 [NC]
RewriteRule ^blog/([0-9]+)/[-0-9a-zA-Z]+/?$ index.php?action=blog&category=$1 [NC]

What I am trying to accomplish is:

domain.com/blog/1/title-of-post and domain.com/blog1/name-of-category

Is this possible? What are my options?

Upvotes: 0

Views: 66

Answers (1)

AbsoluteƵERØ
AbsoluteƵERØ

Reputation: 7880

Since the URIs are slightly different you should be able to use this in .htaccess:

RewriteRule ^blog/([0-9]+) index.php?action=blog&postID=$1 [L]
RewriteRule ^blog([0-9]+)/ index.php?action=blog&category=$1 [L]

We do not need the [NC] flag because we're only matching a number. The [L] flag tells Apache to stop processing if there is a match. Since you're not doing anything with the titles there is no need to search all the way to the end of the line. Once we find the postID or category we should have all of our info.

To match both at the same time you might try this in a single rule.

RewriteRule ^blog([0-9]+)/([0-9]+) index.php?action=blog&category=$1&postID=$2 [L]
RewriteRule ^blog/([0-9]+) index.php?action=blog&postID=$1 [L]
RewriteRule ^blog([0-9]+)/ index.php?action=blog&category=$1 [L]

If you're setting up the Virtual Hosts then you'll have to add the preceding slashes:

RewriteRule ^/blog/([0-9]+) /index.php?action=blog&postID=$1 [L]
RewriteRule ^/blog([0-9]+)/ /index.php?action=blog&category=$1 [L]

Upvotes: 1

Related Questions