What I’m Trying to Accomplish
-
I have more than 1,000 individual files in the format
https://example.com/archives/<NNNNNN>.php
whereN
is an integer. Here is an example. -
For some very complicated historical reasons, I need to keep the existing structure as-is, though I can add to it. In this case, each page has a unique
data-url-title="<url-friendly-title>"
. -
I would like my
.htaccess
config to determine what file was read, use regex to extract theurl-friendly-title
and rewrite the final URL to replace<NNNNNN>
, in the formathttps://example.com/archives/url-friendly-title.php
(I would then strip.php
from it—but I didn’t get that far).
What I Try to Do
# Enable rewriting
RewriteEngine On
# Match the old archive URL
RewriteCond %{REQUEST_URI} ^/archives/([0-9]+).php$
# Check that the file exists
RewriteCond expr "-f '%{DOCUMENT_ROOT}/archives/%1.php'"
# Extract data-url-title from the file content
RewriteCond expr "file('%{DOCUMENT_ROOT}/archives/%1.php') =~ /data-url-title="([^"]+)"/"
# Rewrite the URL to the new friendly URL
RewriteRule ^archives/([0-9]+).php$ /archives/%1.php [R=301,L]
What Happens
Any attempt to use this configuration causes my entire website to throw an internal server error with the log message RewriteCond: bad flag delimiters
.
-
I don’t think I have any spaces in my regex.
-
I’ve converted my
.htaccess
file to Unix endings.
I have looked at numerous accepted answers, and they seem to indicate that, in Apache 2.4.x, it’s completely legitimate to read a variable from an external file by using RewriteCond expr "<expression>"
.
I can’t get this to work. Moreover, the htaccess tester throws Unsupported TestString: expr
for both RewriteCond expr
statements. What am I missing here?