


How to configure CORS (Cross-Origin Resource Sharing) in Apache?
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.
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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.

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

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.

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.

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.

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

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
