Justin
Justin

Reputation: 1956

Using .htaccess to Rewrite URLs with ID and Filename

I am trying to rewrite a URL with .htaccess and had a question that I'm unable to find an answer to after many hours of searching. And, it doesn't help that my regex skills aren't that great...

The underlying format for my URLs is this: http://mysite.com/article.php?id=1.

I would like to have a URL like this direct there: http://mysite.com/article/1/made-up-irrelevant-title-slug.

The problem is, I'd like the article to be a variable such that it could be changed to page and would direct to something like: http://mysite.com/page.php?id=1, from http://mysite.com/page/1/made-up-page-name.

If anyone knows how this is properly written, I would be extremely grateful!

Upvotes: 1

Views: 3064

Answers (1)

nachito
nachito

Reputation: 7035

# Turn on Rewrites
RewriteEngine on

# Do not rewrite existing files, directories, or symlinks.
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]

# Rewrite /COMPONENT/ID/TITLE -> COMPONENT.php?id=ID
RewriteRule ^([^/]+)/(\d+)/.*$ $1.php?id=$2 [L]

Upvotes: 4

Related Questions