How to Set HTTP Headers Using Apache Server?
Last Updated :
21 Jun, 2024
HTTP headers are key-value pairs sent in HTTP requests and responses. They carry essential information about the request or response, such as content type, caching directives, and security policies. Setting HTTP Headers in Apache is a common requirement for enhancing the security, performance and functionality of the web application.
Prerequisites
- Apache server Installed.
- Access to Apache configuration files.
- Content-Type: Indicates the media type of the resource.
- Cache-Control: Directs caching mechanisms on how and when to cache responses.
- Strict-Transport-Security (HSTS): Enforces secure (HTTP over SSL/TLS) connections.
- X-Content-Type-Options: Prevents browsers from MIME-sniffing a response away from the declared content type.
- X-Frame-Options: Controls whether a browser should be allowed to render a page in a <frame>, <iframe>, <embed>, or <object>.
- Content-Security-Policy (CSP): Prevents cross-site scripting (XSS), clickjacking, and other code injection attacks.
There are several methods to set the HTTP headers using apache server which are as follows:
Using`.htaccess` File
This file can be used to set the HTTP headers at a directory level from where the apache servers the pages. commonly form the htdocs directory inside the Apache folder.
Step 1: Open or create a `.htaccess` file in a root directory lets say htdocs as it is a default one. And then add the following directives:
# Enforce HTTPS
<IfModule mod_headers.c>
Header set Strict-Transport-Security "max-age=31536000; includeSubDomains"
</IfModule>
# Prevent MIME type sniffing
<IfModule mod_headers.c>
Header set X-Content-Type-Options "nosniff"
</IfModule>
# Prevent clickjacking
<IfModule mod_headers.c>
Header always append X-Frame-Options SAMEORIGIN
</IfModule>
# Content Security Policy
<IfModule mod_headers.c>
Header set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; object-src 'none'"
</IfModule>
Step 2: Save the .htaccess file.
Step 3: Restart Apache. To do this, open the Command Prompt as an administrator and run:
httpd -k restart
Step 4: If apache is not started run following command:
httpd -k start
Modifying the Apache Configuration File
To apply the http header at server level we need to edit the configuration file(`httpd.conf`).
Example: Setting Cache-Control Header
Step 1: Locate apache configuration file.
Path:
`C:\Apache24\conf\httpd.conf`.
Step 2: Open httpd.conf in text editor like Notepad.
Step 3: Add the following directives.
<IfModule mod_headers.c>
# Add a custom header for all responses
Header add X-Header "geek for geeks"
# Add a custom security header
Header add Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
# Add CORS headers
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header add Access-Control-Allow-Headers "Content-Type, Authorization"
</IfModule>
Step 4: Save the file.
Step 5: Restart Apache using the Command Prompt as an administrator:
httpd -k restart
Step 6: If apache is not started run following command:
httpd -k start
Virtual Host Configuration
to set the headers for a specific website you need to configure them within the virtual host configuration.
Example: Setting X-Frame-Options Header
Step 1: Open the virtual hosting config file for your site.
Path:
`C:\Apache24\conf\extra\httpd-vhosts.conf`.
Step 2: Add the following directives inside the appropriate <VirtualHost> block:
<VirtualHost *:80>
ServerName example.com
DocumentRoot "C:/Apache24/htdocs/example.com"
<IfModule mod_headers.c>
# Add a custom header for all responses
Header add X-Header "geek for geeks"
# Add a custom security header
Header add Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
# Add CORS headers
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header add Access-Control-Allow-Headers "Content-Type, Authorization"
</IfModule>
</VirtualHost>
Step 3: Save the file.
Step 4: Restart Apache using the Command Prompt as an administrator:
httpd -k restart
Step 5: If apache is not started run following command:
httpd -k start
To verify the header we set in our apache server using above methods we simply navigate to the command prompt and request the url using curl to get the headers as follwos:
curl I - http//localhost:portNum
HTTP headers set in apache are retrived.In my case Iam using the port 809 to check yours visit the httpd file and press ctrl+f and enter por click enter. check the port and change url accordingly.
Conclusion
Configuring HTTP headers in Apache server is must for enhancing your website's security and performance. Whether using the .htaccess file, the main configuration file, or virtual host configurations, ensure you regularly update your headers to make your server more secured.
Similar Reads
HTTP headers | Server-Timing
The HTTP Server-Timing header is a response-type header. This header is used to communicate between two or more metrics and descriptions for a given request-response cycle from the user agent. The HTTP Server-Timing header is useful to any back-end server timing metrics like read or write in any dat
2 min read
How to Use JMeter's HTTP Header Manager?
Apache JMeter is a famous open-source tool used to load-test functional behavior and measure performance. So today we are going to see how HTTP Header Manager can be so useful, its functionality is directly related to the management of headers on your HTTP Request. Needless to say, for sending the i
6 min read
How to Hide Apache Server Signatures?
When you visit a website, the server sends back information about itself, including a signature that can be exploited by attackers. To enhance website security, you can hide this signature. For Apache servers, adjust the "ServerSignature" and "ServerTokens" settings in the configuration file to disa
4 min read
How to Host Apache HTTP Server on Microsoft Windows?
Apache HTTP Server, commonly known as Apache, is a widely used, powerful, and secure web server it is an ideal choice for hosting web applications. Popular deployment options include Apache Lounge, Bitnami WAMP Stack, WampServer, and XAMPP. Each option has its advantages and disadvantages, but in th
3 min read
How to Enable CORS in Apache Web Server?
Cross-Origin Resource Sharing(CORS) is a security feature that allows web browsers to make requests to a different domain than the one serving the web page. without CORS, browsers restrict such requests due to security concerns. Enabling CORS ensures that your web server responds correctly to cross-
2 min read
How to add HTTP headers 'X-Frame-Options' on iframe ?
Inline frame tag in HTML: The iframe tag is used to displaying or embedding another document within an HTML document. One of its attributes 'src' is used to specify the URL of the document which is to be displayed. A site's X-frame Options can prevent allowing the display of one HTML document within
2 min read
How to Change the Root Directory of an Apache server?
The directory that the Apache web server searches for files to provide upon a client's request is known as the DocumentRoot.By default, the DocumentRoot is usually set to something like /var/www/html on the Linux operating system. You can serve files from a different directory by changing this.Steps
2 min read
How to Enable & Set Up .htaccess File on Apache?
The .htaccess is a simple but extremely powerful configuration file used by the web servers running on apache web server software. this .htaccess file allow to alter and change their configuration of the main configuration files without even having direct access to them. In this guide, we will look
3 min read
How to Enable HTTP Strict Transport Security (HSTS) for Apache?
HTTP Strict Transport Security (HSTS) is a security policy component that assists with safeguarding sites against protocol for downsize attacks and cookies highjacking by forcing the HTTPS connections. Using HSTS on your Apache web server improves the security of your site.PrerequisitesAccess: Admin
5 min read
Servlet - HTTP Status Codes
For each HTTP request and HTTP response, we have messages. The format of the HTTP request and HTTP response messages are similar and will have the following structure â An initial status line + CRLFCRLF = Â ( Carriage Return + Line Feed i.e. New Line )Zero or more header lines + CRLFA blank line, i.e
4 min read