Adrien Hingert
Adrien Hingert

Reputation: 1516

Back-reference variables in multiple RewriteCond with .htaccess

I have a URL in the form of:
https://example.com/subfolder1/subfolder2/page1.htm?cid=1234abcd

Both subfolder1 & subfolder2 and page1 can have many values. The URL can have just the cid query parameter, more query parameters or none at all. In case the URL has more query parameters, these must be kept.

How do I change this URL to the following in .htaccess?
https://example.com/subfolder1/subfolder2/page1-1234abcd.htm?cid=1234abcd

The URL should not be rewritten if the parameter is already present in the URL. This can be verified by the presence of a hyphen followed by 8 alphanumeric characters and then followed by .htm.

The rewritten URL should be visible in the URL bar and should allow further rules to be processed.

I've tried the following, but I can't seem to be able to write the variables in the RewriteRule:

RewriteEngine On  
RewriteCond %{QUERY_STRING} (^|&)cid=([0-9a-zA-Z]*)(&|$)  
RewriteCond %{REQUEST_URI} !\-([0-9a-zA-Z]{8})\.htm  
RewriteCond %{REQUEST_URI} /([^/]*)/([^/]*)/([0-9a-zA-Z]*)\.htm  
RewriteRule ^ /%1/%2/%3-%5.htm [R=301,L,QSA]  

All the variables referenced are not shown in the URL. I understand that the % variables only reference the last RewriteCond so I tried using RewriteRule ^ - [E=cid:%2] after the first RewriteCond and then using %{ENV:cid} instead of %5, but it still doesn't work.

This is what I see: https://example.com///-.htm?cid=1234abcd

Any ideas on what I'm doing wrong?

Upvotes: 0

Views: 20

Answers (1)

Adrien Hingert
Adrien Hingert

Reputation: 1516

I managed to solve it with this:

RewriteCond %{THE_REQUEST} /([^/]*)/([^/]*)/([0-9a-zA-Z]*)\.htm?(.*)cid=([0-9a-zA-Z]{8})
RewriteRule ^ /%1/%2/%3-%5.htm [R=301,L,QSA]

Mods please close if irrelevant

Upvotes: 0

Related Questions