简体   繁体   中英

Help convert Apache rewrite rules to PHP regular expressions

Short story: I am using this technique to auto-version my css and js files by adding a string to the filename with filemtime(): http://w-shadow.com/blog/2012/07/30/automatic-versioning-of-css-js/

I got it up and running perfectly on my local machine (MAMP), but I use WP Engine for my hosting and they are set up on nginx and don't support .htaccess rewrite rules.

They do have a place to enter PHP regular expressions (preg_replace), though, and their instructions look like this:

HTML Post-Processing
A mapping of PHP regular expressions to replacement values which are executed on all blog HTML after WordPress finishes emitting the entire page. The pattern and replacement behavior is in the manner of preg_replace().

The following example removes all HTML comments in the first pattern, and causes a favicon (with any filename extension) to be loaded from another domain in the second pattern:

#<!--.*?-->#s =>

#\\bsrc="/(favicon\\..*)"# => src="http://mycdn.somewhere.com/$1"

. So I'm wondering how hard it is to convert this rewrite rule to a PHP regular expression:

RewriteRule ^(.*)\\.[\\d]{10}\\.(css|js)$ $1.$2 [L]

And if this would even be doing the same thing as the apache rewrite. the whole point of the technique is to bust the browser cache for css or js files and time they are changed, but without resorting to query strings, which have various drawbacks.

Actually, it's pretty much the same. Take your regex, delimit it, drop it in a string and escape the right things, then take your rewrite rule and use single quotes to make it a string, and you're done. In your example:

$newUrl = preg_replace('/^(.*)\\.[\\d]{10}\\.(css|js)$/', '$1.$2', $url);

This will properly rewrite anything url you give it. However, it sounds like these preg_replaces are being done across a large document, which means your regex there won't do what you think it will. That, however, is a completely separate question. One I won't even guess at, because I don't know what your requirements are. If you need help crafting the regex, please open another question with your specific requirements.

Also: Next time, Check the documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM