AKS
AKS

Reputation: 4658

Apache rewrite condition get second regex match

I''m sorry for asking the millionth Apache rewrite question here. I tried everything I know, but there is a small (hopefully) step that I'm looking for someone to shed a light for me.

I have a URL structure similar to this:

 - assets
 - assets/dist/19854/css/my.css
 - css/my.css

I'm trying to rewrite assets/dist/19854/css/my.css file to css/my.css file in the root.

I have mod_rewrite enabled on my server, and I have basic understanding of rewrite rules, but it would be great if you could assist me with the Regex.

RewriteCond %{REQUEST_URI} ^assets/dist/([0-9/.]+)/(.*)$
RewriteRule ^assets/dist/([0-9]+)/(.*)$ $ [L,QSA]

Problem with the above rule is the it rewrite to ./19854, but I'm actually interested in the second expression's match. If possible, I'd also like to make sure the css/my.css file exists first.

Thanks in advance!

Edit:

Thanks for the comments and the answer. To further explain my case, this is a small site that uses a CDN, and everytime a new build is up, the number in assets/dist/[0-9] gets changed, so all assets' source URL gets changed. But I'm using a CSS compiler to compile CSS files, so CSS files reside in the same folder (css/my.css). I have some other rewrites so I'm making my RewriteConds more strict.

So far, the above rewrite matches the numeric part, but I'm trying to rewrite to the URL right after the numeric part.

current match

Upvotes: 1

Views: 1014

Answers (1)

anubhava
anubhava

Reputation: 785541

I believe you're attempting in other way round. You can use this code in your DOCUMENT_ROOT/.htaccess file:

RewriteEngine On
RewriteBase /

# route to /css/my.css if it exists
RewriteCond %{DOCUMENT_ROOT}/$1 -f [NC]
RewriteRule ^assets/dist/.+?/(css/my\.css)$ $1 [L,NC]

Upvotes: 3

Related Questions