Search code examples
regexapache.htaccessmod-rewrite

htaccess Rewrite rule for anything after the domain


I've got a one page website that just has a switch that replaces some content with a local town names.

The normal domain.com will go to index.php, but I want anything after the domain to be passed in the GET query.

So domain.com/nottingham would go to index.php?town=nottingham

I have around 300 town names, so I dont ant to hardcode them all so I'm trying to get the $1 to pass the value and it doesn't seem to work.

I've got the following in my .htaccess

RewriteEngine On

RewriteRule ^([a-zA-Z0-9])$ /index.php?town=$1 [NC,L]

ErrorDocument 404 /index.php

But when I try domain.com/townname I get "Warning: Undefined array key "town" in..." So I assume thats missing my rewriterule and gonig to the 404.


Solution

  • You forgot to include a quantifier in your pattern - [a-zA-Z0-9] means allow for one character out of this character group. And since you anchored your pattern at the start and end, it would match when you requested domain.com/t, but not with any path component longer than that.

    Add the + quantifier after the character group, to say "a character matching this group, one or more times":

    RewriteRule ^([a-zA-Z0-9]+)$   /index.php?town=$1 [NC,L]