Skip to content

Instantly share code, notes, and snippets.

@heywens
Last active April 19, 2023 14:07
Show Gist options
  • Save heywens/b6990b698a2013b462e0862abea7ccf2 to your computer and use it in GitHub Desktop.
Save heywens/b6990b698a2013b462e0862abea7ccf2 to your computer and use it in GitHub Desktop.
Apache CORS (For Development Mode Only)

Here's a sample VirtualHost configuration to enable CORS (Cross-Origin Resource Sharing) on Apache, allowing my React app to connect to server (Laravel) during development.

Listen 8080
NameVirtualHost *:8080

<VirtualHost *:8080>
	ServerAdmin webmaster@dummy-host.example.com
	DocumentRoot "/Users/wens/dev/laravel/public"
	ServerName dummy-host.example.com
	ServerAlias www.dummy-host.example.com

	Header set Access-Control-Allow-Origin "http://localhost:3000"
	Header set Access-Control-Allow-Credentials "true"
	Header set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
	Header set Access-Control-Max-Age "1000"
	Header set Access-Control-Allow-Headers "x-xsrf-token, x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

	<Directory "/Users/wens/dev/laravel/public">
		AllowOverride All
		Order allow,deny
		Allow from all
	</Directory>
</VirtualHost>

To allow other clients to access the development server, you can add the following configuration in your VirtualHost definition as shown below:

	# Header set Access-Control-Allow-Origin "http://localhost:3000"
	<IfModule mod_headers.c>
		SetEnvIf Origin "http(s)?://(www\.)?((localhost|19.168.8.101|19.168.8.102)(:?(3000|8889))$" AccessControlAllowOrigin=$0
		Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
		Header merge Vary Origin
	</IfModule>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment