kvanbere
kvanbere

Reputation: 3352

mod_rewrite accept only dashes & alphanumeric, otherwise throw 404

I'm using mod_rewrite to transfer the end of the URL to my php script which will act as a microcms. My url will look something like this: mysite.com/articles/some-article-about-css

That will pass the following to my PHP script index.php: index.php?action=read&article=some-article-about-css

I have questions:

  1. I'm unsure how the best way to only accept alphanumeric w/ dashes using mod_rewrite. I found this rule on the internet ((?:[a-z]+)?(?:[0-9]+)?-?)+ and it apparently doesn't allow double dashes which is even better, but its long and confusing. Is there another (shorter, faster) rule I can use?

  2. I'd like to verify that this rule is valid for what I'm trying to accomplish. I'm not very good with mod_rewrite: RewriteRule ^/articles/((?:[a-z]+)?(?:[0-9]+)?-?)+ /index.php?action=read&article=$1

  3. What rule can I use so that if the url after /articles/ is not a valid alphanumeric /w dashes url, automatically throw a 404 rather than passing to my script?

Upvotes: 1

Views: 4183

Answers (2)

Andrew Leap
Andrew Leap

Reputation: 956

RewriteRule ^/articles/([a-zA-Z0-9-]*) /index.php?action=read&article=$1 [QSA,L]

RewriteRule ^/articles/ - [R=404]

For alphanumeric and dashes only

Upvotes: 2

safarov
safarov

Reputation: 7804

You dont need that complex regex i believe. Try this

RewriteRule ^articles/([^a-zA-Z0-9-]*) /index.php?page=$1 [L]
RewriteRule ^articles(.*) [R=404]

Upvotes: 1

Related Questions