How to Set Apache Request Headers Conditionally

set apache request headers conditionally

Sometimes, you might need to add specific request headers based on certain conditions, so you can process it downstream accordingly. Apache allows you to do this in multiple ways. Let us take a look at how to set Apache request headers conditionally.


How to Set Apache Request Headers Conditionally

Here are the steps to set Apache request headers conditionally.


1. Open Apache config file

Open Apache’s config file in a text editor.

$ sudo vim /etc/apache2/apache2.conf


If you are unable to locate Apache config file at the above location, look at the following locations:


  • /etc/apache2/httpd.conf
  • /etc/httpd/httpd.conf
  • /etc/httpd/conf/httpd.conf


2. Set Request Headers Conditionally

Let’s say you want to add the header Access-Control-Allow-Origin: *

In that case, add the following lines to your Apache config file

SetEnvIf Request_URI somepartofurl SIGN
Header always add "Access-Control-Allow-Origin" "*" env=SIGN

The above code will work only if it is placed in Apache config file. I haven’t tried it in location and Directory blocks.


If you don’t have access to your config file, you can add the following code to your .htaccess file.

RewriteRule ^/en/foo.*$ - [ENV=SET_ACAO:true]
Header set "Access-Control-Allow-Origin" "*" env=SET_ACAO

Where ^/en/foo.*$ is a Regex for the URL to be matched.

The above code can be placed in Location as well as Directory blocks.


Please ensure you have enabled .htaccess for the above code to work.

Here’s how you can enable .htaccess (mod_rewrite):


Place your .htaccess file in the root document folder of your website (/var/www/html)


3. Restart Apache web server

Restart Apache web server to apply changes

$ sudo /etc/init.d/apache2 start [Debian or Ubuntu]
# sudo apachectl restart [RHEL, CentOS or Fedora]


That’s it! Now Apache will automatically set request headers conditionally for specific URLs, locations and directories, based on your requirements.


About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!