Šime Vidas
Šime Vidas

Reputation: 185933

Trouble with URL rewriting in .htaccess

My .htaccess file looks like this:

RewriteEngine On
RewriteRule ^articles/(\d+)*$ ./articles.php?id=$1

So, if the URL foo.com/articles/123 is requested, control is transferred to articles.php?id=123.

However, if the requested URL is:

foo.com/articles/123/

or

foo.com/articles/123/whatever

I get a "404 Not Found" response.

I would like to call articles.php?id=123 in all these cases. So, if the URL starts with foo.com/articles/[digits]... no matter what other characters follow the digits, I would like to execute articles.php?id=[digits]. (The rest of the URL is discarded.)

How do I have to change the regular expression in order to achieve this?

Upvotes: 1

Views: 234

Answers (2)

mario
mario

Reputation: 145482

You do need to allow the trailing / with:

RewriteRule ^articles/(\d+)/?$

The \d+ will only match decimals. And the $ would disallow matches beyond the end.

If you also need trailing identifiers, then you need to allow them too. Then it might be best to make the match unspecific:

RewriteRule ^articles/(.+)$

Here .+ matches virtually anything.

But if you want to keep the numeric id separate then combine those two options:

RewriteRule ^articles/(\d+)(/.*)?$   ./articles.php?id=$1

Upvotes: 2

hakre
hakre

Reputation: 197767

Just don't look for the end:

RewriteRule ^articles/(\d+) ./articles.php?id=$1

Upvotes: 2

Related Questions