Table of Contents
Enable mod_headers Module
Set CORS Headers in Configuration
Allow Multiple Origins or Wildcard
Handle Preflight Requests (OPTIONS)
Home Operation and Maintenance Apache How to configure CORS (Cross-Origin Resource Sharing) in Apache?

How to configure CORS (Cross-Origin Resource Sharing) in Apache?

Sep 15, 2025 am 12:45 AM
apache cors

To configure CORS in Apache, enable the mod_headers module using a2enmod headers or uncommenting the LoadModule directive, then set Access-Control-Allow-Origin, Methods, and Headers in .htaccess or virtual host files, use wildcards or environment variables for multiple origins, include Vary: Origin, and handle preflight OPTIONS requests with proper headers and rewrite rules.

How to configure CORS (Cross-Origin Resource Sharing) in Apache?

To configure CORS (Cross-Origin Resource Sharing) in Apache, you need to set specific HTTP response headers that allow browsers to permit cross-origin requests. This is commonly done using the mod_headers module and directives in your Apache configuration files (e.g., httpd.conf, .htaccess, or virtual host files).

Enable mod_headers Module

Ensure the mod_headers module is enabled, as it’s required to set CORS headers.

  • On Debian/Ubuntu: Run a2enmod headers and restart Apache.
  • On CentOS/RHEL: Make sure LoadModule headers_module modules/mod_headers.so is uncommented in httpd.conf.
  • After enabling, restart Apache: sudo systemctl restart apache2 or sudo systemctl restart httpd.

Set CORS Headers in Configuration

Add the following directives to your Apache configuration to enable CORS:

  • In a .htaccess file (in your web root):


 Header set Access-Control-Allow-Origin "https://example.com"
 Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
 Header set Access-Control-Allow-Headers "Content-Type, Authorization"

  • In a virtual host or main config file, place the same inside a or block.

Allow Multiple Origins or Wildcard

If you need to allow any domain (less secure), use:

Header set Access-Control-Allow-Origin "*"

For dynamic origins (e.g., based on request), use environment variables or rewrite rules. Example with conditional header:

SetEnvIf Origin "https://(.*\.?)example\.com$" ACAO=$0
Header set Access-Control-Allow-Origin %{ACAO}e env=ACAO
Header set Vary "Origin"

Handle Preflight Requests (OPTIONS)

Browsers send an OPTIONS request before certain cross-origin requests. Ensure Apache responds properly:

Header always set Access-Control-Max-Age "86400"
Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With"

You may also add:

RewriteEngine On
RewriteCond %{REQUEST_METHOD} ^OPTIONS$
RewriteRule .* - [R=200,L]

Basically just set the right headers and handle OPTIONS correctly. It's not complex but easy to miss a step.

The above is the detailed content of How to configure CORS (Cross-Origin Resource Sharing) in Apache?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build a PHP Nginx environment with MacOS to configure the combination of Nginx and PHP services How to build a PHP Nginx environment with MacOS to configure the combination of Nginx and PHP services Jul 25, 2025 pm 08:24 PM

The core role of Homebrew in the construction of Mac environment is to simplify software installation and management. 1. Homebrew automatically handles dependencies and encapsulates complex compilation and installation processes into simple commands; 2. Provides a unified software package ecosystem to ensure the standardization of software installation location and configuration; 3. Integrates service management functions, and can easily start and stop services through brewservices; 4. Convenient software upgrade and maintenance, and improves system security and functionality.

How to use Kubernetes to keep PHP environment consistent Production and local container configuration standards How to use Kubernetes to keep PHP environment consistent Production and local container configuration standards Jul 25, 2025 pm 06:21 PM

To solve the problem of inconsistency between PHP environment and production, the core is to use Kubernetes' containerization and orchestration capabilities to achieve environmental consistency. The specific steps are as follows: 1. Build a unified Docker image, including all PHP versions, extensions, dependencies and web server configurations to ensure that the same image is used in development and production; 2. Use Kubernetes' ConfigMap and Secret to manage non-sensitive and sensitive configurations, and achieve flexible switching of different environment configurations through volume mounts or environment variable injection; 3. Ensure application behavior consistency through unified Kubernetes deployment definition files (such as Deployment and Service) and include in version control; 4.

How to resolve apache cannot load libphp.so into server How to resolve apache cannot load libphp.so into server Aug 08, 2025 am 06:07 AM

First,verifythelibphp.sofileexistsusingfindorlocatecommands;ifmissing,reinstallPHPwithApachesupportviapackagemanager.2.CheckApacheconfigurationfilesforcorrectLoadModuledirectivepathandremoveduplicates.3.EnsureApacheandPHPversionsandarchitecturesmatch

How to configure KeepAlive in Apache? How to configure KeepAlive in Apache? Aug 03, 2025 am 07:06 AM

KeepAliveOn enables persistent connections; 2.MaxKeepAliveRequests100 sets the maximum number of requests per connection; 3.KeepAliveTimeout5 sets the timeout for waiting for subsequent requests, restart Apache after configuration and use curl or browser developer tools to verify whether KeepAlive is effective to optimize server performance.

How to install a Let's Encrypt SSL certificate on Apache? How to install a Let's Encrypt SSL certificate on Apache? Aug 04, 2025 am 09:47 AM

Install Certbot and its Apache plug-in; 2. Run Certbot to obtain the certificate and configure the domain name; 3. Optionally configure automatic redirection from HTTP to HTTPS; 4. Set up automatic renewal and pass dry-run test; 5. Verify the installation and ensure the normal reload configuration of Apache. After the certificate is successfully deployed, renewal will be automatically managed. After the entire process is completed, secure HTTPS access can be achieved.

PHP realizes image upload and processing monetization PHP image management and optimization technology PHP realizes image upload and processing monetization PHP image management and optimization technology Jul 25, 2025 pm 06:06 PM

Effectively managing massive images requires CDN or cloud storage to improve performance and scalability; 2. Optimize file structure through reasonable naming rules and directory storage; 3. Use PHP to automatically compress and convert it into efficient formats such as WebP to reduce volume; 4. Combine front-end responsive images and lazy loading technology to improve loading speed; 5. Realize signature URL anti-theft chain and upload security verification to prevent malicious files, thereby building a safe and efficient picture system to support commercial monetization.

How to choose the right MPM for Apache? How to choose the right MPM for Apache? Jul 26, 2025 am 03:59 AM

ThebestApacheMPMdependsonyourapplicationstackandtrafficneeds:1.UsePreforkifrelyingonnon-thread-safemoduleslikemod_phpandprioritizingstability.2.UseWorkerformoderatetohightrafficwiththread-safesetupsandbettermemoryefficiency.3.UseEventforhighconcurren

Where is the Apache configuration file? Where is the Apache configuration file? Aug 08, 2025 am 01:20 AM

OnDebian/Ubuntu,themainApacheconfigurationfileis/etc/apache2/apache2.conf,withadditionalconfigurationsin/etc/apache2/sites-available/and/etc/apache2/conf-available/.2.OnRHEL/CentOS/Fedora,itistypically/etc/httpd/conf/httpd.conf,withextrafilesin/etc/h

See all articles