Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex search and replace on Apache header edit

Tags:

regex

apache

pcre

I have the next code on a .htaccess file

<IfModule mod_headers.c>
        Header set Content-Security-Policy "base-uri http://site.local/"
        Header append Content-Security-Policy "default-src 'none'"
        Header append Content-Security-Policy "connect-src 'self'"
        Header append Content-Security-Policy "style-src 'self'"
        Header edit Content-Security-Policy "," ";"
</IfModule>

which generates the next response header from the server:

Content-Security-Policy base-uri http://site.local/, default-src 'none', connect-src 'self', style-src 'self'

I want to get that line with semicolons instead of commas, like this:

Content-Security-Policy base-uri http://site.local/; default-src 'none'; connect-src 'self'; style-src 'self'

Using append or merge on Apache's mod_headers separates the different additions to the header previously set with a comma, as the standard seems to point, but the W3C dictates that the different configurations of the Content Security Policy have to be separated with a semicolon.

I can't find a way to write the Header edit line to replace the ',' with ';' as per the W3C states.

I have tried many variations for the search, I know that some are wrong but since I'm not getting the expected results I'm trying anything that I can think of.

I have tried patterns like this:

  • "," with and without quotes, both replace the first occurrence only.
  • /,/ with and without quotes, nothing happens.
  • /,/g with and without quotes, nothing happens.
  • ...

What am I missing?

like image 219
PatomaS Avatar asked Mar 30 '26 16:03

PatomaS


1 Answers

Header directive accepts two different arguments in order to perform a substitution. The one that performs a global match has a trailing asterisk edit*. From documents:

The edit form will match and replace exactly once in a header value, whereas the edit* form will replace every instance of the search pattern if it appears more than once.

You need edit* as in:

Header edit* Content-Security-Policy , ;
like image 79
revo Avatar answered Apr 02 '26 13:04

revo