apache.htaccessmod-rewritemod-headers

Apache RewriteRule: bad flag delimiters "FilesMatch"


This is my .htaccess file in the head

<FilesMatch "\.pdf$">
    RewriteRule ([^/]+)\.pdf $ - [E=FILENAME:$1]
    <If "%{REQUEST_URI} =~ m#^/wp-content/themes/my_theme/pdf/fr/.*#">
        Header add Link '<https://www.example.com/wp-content/my_theme/theme_SES/pdf/fr/%{FILENAME}e>; rel="canonical"'
    </If>
</FilesMatch>

And I'm receiving the following error in the error.log:

RewriteRule: bad flag delimiters

What's wrong with the .htaccess file?


Solution

  • RewriteRule ([^/]+)\.pdf $ - [E=FILENAME:$1]
    ------------------------^
    

    You have an erroneous space before the $. So the - is being seen as the flags (3rd) argument, hence the error.

    It should be written like this:

    RewriteRule ([^/]+)\.pdf$ - [E=FILENAME:$1]
    

    Aside: You should be OK in this instance, but note the following warning from the docs:

    Although rewrite rules are syntactically permitted in <Location> and <Files> sections (including their regular expression counterparts), this should never be necessary and is unsupported. A likely feature to break in these contexts is relative substitutions.

    For example, your code block could be rewritten more simply as:

    RewriteRule ^wp-content/themes/my_theme/pdf/fr/(?:.+/)?([^/]+)\.pdf$ - [E=FILENAME:$1]
    Header add Link '<https://www.example.com/wp-content/my_theme/theme_SES/pdf/fr/%{FILENAME}e>; rel="canonical"' env=FILENAME
    

    This could perhaps be simplified further knowing your actual URL structure.

    And, depending on your other directives, you may need to change FILENAME in the Header directive to REDIRECT_FILENAME. (Depending on whether there is a loop by the rewrite engine - which there usually is if the standard WordPress directives are being used.)

    Note the addition of the env=FILENAME argument on the Header directive, which sets this header conditionally on whether the FILENAME env var is set.