I know there are many similar out there but I did not find a working solution for me.
I have incoming URLs like: https://example.com/123-frank-street
and want them to rewrite to: https://example.com/street/index.php?name=123-frank-street
I tried dozens of versions and my closest is the following
RewriteRule ^[0-9] ([A-Za-z0-9-] )/?$ /street/index_test.php?street=$1 [NC,L]
This only rewrites to: https://example.com/street/index.php?name=-frank-street
The 123 is missing and gets somehow not forwarded. only the rest! What I am missing here or doing wrong?
thx in advance
CodePudding user response:
Rewrite rules are really quite simple once you understand their structure:
- On the left is a regular expression which determines which URLs from the browser the rule should match
- Inside that regular expression, you can "capture" parts of the URL with parentheses
()
- Next, is the URL you want to serve instead; it can include parts that you captured, using numbered placeholders
$1
,$2
, etc. It's entirely up to you where you put these, and Apache won't guess - Finally, there are flags which act as options; in your example, you're using "NC" for "Not Case-sensitive", and "L" for "Last rule, stop here if this matches"
In your example, the pattern you are matching is ^[0-9] [A-Za-z0-9-] /?$
, which is "from start of URL, 1 or more digits, one or more letters/digits/hyphens, 0 or 1 trailing slash, end of URL".
The only part you're capturing is ([A-Za-z0-9-] )
, the "one or more letters/digits/hyphens" part; so that is being put into $1
. So the rest of the URL is being "discarded" simply because you haven't told Apache you want to put it anywhere.
If you want to capture other parts, just move the parentheses, or add more. For instance, if you write ^([0-9] )([A-Za-z0-9-] )/?$
then $1
will contain the "one or more digits" part, and $2
will contain the "one or more letters/digits/hyphens" part.