dokku / dokku

A docker-powered PaaS that helps you build and manage the lifecycle of applications
https://dokku.com
MIT License
29.3k stars 1.92k forks source link

CORS support? What's the simplest way? #997

Closed MichaelJCole closed 9 years ago

MichaelJCole commented 9 years ago

Hi, I want to CORS every subdomain on my server (*.example.com)

What's the best way to do that in Dokku?

This came up as a replacement for vhosts: https://github.com/chrisfranklin/nginx-vhosts

Enable-cors.org has a guide that's pretty popular, but doesn't seem immediately compatible: http://enable-cors.org/server_nginx.html

Any suggestions?

MichaelJCole commented 9 years ago

Here's what I came up with:

1) Use Dokku 3.14+

2) create your app (api.server.com in this exampe):

ssh root@server.com
dokku apps:create api

3) Add nginx SSL CORS template

The default templates are at: /root/dokku/plugins/nginx-vhosts/templates

We're configuring the external port, so we start with the nginx.ssl.conf template. Below is a gist of the template I use. Find more info at http://enable-cors.org/server_nginx.html

Editing templates:

cd /home/dokku/api
wget https://gist.githubusercontent.com/MichaelJCole/2d6d30c6d4e19495c425/raw/ddd1d66ab5d30a8bebc55c0604222d7bc99b8e63/nginx.conf.template
chown dokku:dokku nginx.conf.template

5) Rebuild the apps nginx config.

Compile your new template, and check it's syntax.

dokku nginx:build-config api
nginx -t

Deploying the code will rebuild the config, but not check its syntax (nginx -t)

6) Test it:

curl -I -H "Origin: https://www.server.com" https://api.server.com/r_u_up

You should see Access-Control-Allow-Origin: https://www.server.com in the output.

NOTE: This configuration doesn't allow you to configure CORS in your app itself. E.g. with a middleware like express-cors.

The configuration will enable CORS for any request from the same $VHOST.

This code in the template decides who CORS and who can't.

    if (\$http_origin ~* (^https?://.*\.$VHOST$)) {
        set \$cors corson;
    }
    if (\$http_origin ~* (^http://(localhost|127.0.0.1)(:[0-9]+)?$)) {
        set \$cors corson;
    }
josegonzalez commented 9 years ago

Yep, making your own template is the way to go here. We've documented how to create your own template in the docs :)

qrush commented 8 years ago

A heads up for people who find this issue in the future: you can embed this and other NGINX configurations in nginx.conf.sigil in your app, and dokku will load it for you. Here's an example of a pretty open CORS + SSL template:

https://github.com/qrush/skyway/blob/master/nginx.conf.sigil

josegonzalez commented 8 years ago

The documentation for this is here.

gwasky commented 5 years ago

@MichaelJCole conf file is rebuilt on the next in the api deployment via git