Veljko
Veljko

Reputation: 51

Enable Laravel CORS in NGINX powered by Docker

I have issue with nginx and laravel that i can't fix.

My current setup is laravel on backend, and nuxt on frontend, everything is running by Docker compose. I can't setup cors to work.

Docker-compose.yml

version: '3'

services:
    nginx:
    image: nginx:stable-alpine 
    container_name: a-nginx 
    ports:
        - 88:80
    volumes:
        - ./server:/var/www/html
        - ./default.conf:/etc/nginx/conf.d/default.conf
    links:
        - php
        - nuxt

php:
    build:
        context: .
        dockerfile: Dockerfile 
    container_name: a-php 
    volumes: 
        - ./server:/var/www/html
        - ./custom.ini:/usr/local/etc/php/conf.d/custom.ini
    ports:
        - "9000:9000"

nuxt:
    image: node:10.15.1
    container_name: a-client 
    command: npm run dev
    volumes: 
        - ./client:/usr/src/app
    working_dir: /usr/src/app
    ports:
        - "3000:3000"
    environment:
        HOST: 0.0.0.0

default.conf

server {
   listen 80;
   charset utf-8;

  location / {
    proxy_redirect                      off;
    proxy_set_header X-Real-IP          $remote_addr;
    proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto  $scheme;
    proxy_read_timeout                  1m;
    proxy_connect_timeout               1m;

    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;

    proxy_pass http://a-client:3000;
}

location ~ ^/(api|storage)/ {
    proxy_pass http://a-nginx:81;
}

}

server { listen 81;

index index.php index.html;
root /var/www/api/public;
charset utf-8;

location / {
    try_files $uri $uri/ /index.php?$is_args$args;
}

location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt  { access_log off; log_not_found off; }

error_page 404 /index.php;

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass php:9000;
    fastcgi_index index.php;
    fastcgi_read_timeout 1000;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
}

location ~ /\.(?!well-known).* {
    deny all;
}

}

I tried basically every solution on internet, but none work.

Console on client shows this warning: Client console

Upvotes: 0

Views: 4082

Answers (1)

Raj Srujan Jalem
Raj Srujan Jalem

Reputation: 661

Try adding CORS headers in your nginx conf:

add_header Access-Control-Allow-Origin *;
add_header Access-Control-Max-Age 3600;
add_header Access-Control-Expose-Headers Content-Length;
add_header Access-Control-Allow-Headers Range;

For enabling CORS in nuxt: See CORS blocking client request in Nuxt.js

Upvotes: 1

Related Questions