What is the Same-Origin Policy in Browsers?#
The Same-Origin Policy restricts how documents or scripts loaded from one origin can interact with resources from another origin. It is an important security mechanism used to isolate potentially malicious files.
Same-origin refers to having the same "protocol + domain + port". Even if two different domain names point to the same IP address, they are not considered same-origin.
How to Achieve Cross-Origin Resource Sharing?#
Cross-origin resource sharing has been a long-standing issue, and there have been many historical approaches to solving it. In this article, we will mainly focus on Nginx's cross-origin solution and not delve into other solutions.
Convenient Cross-Origin Solution with Nginx#
Nginx is an extremely powerful web server known for its lightweight nature, fast startup, and high concurrency.
In most new projects, Nginx is the preferred choice. Services developed using Node.js or Go usually need to go through Nginx's reverse proxy.
The principle of reverse proxy is simple: all client requests must first go through Nginx for processing. Nginx acts as a proxy server and forwards the requests to Node.js or Go services. This way, the same-origin policy is bypassed.
# Number of worker processes, can be adjusted based on CPU count
worker_processes 1;
events {
# Number of connections
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
# Connection timeout, the server will close the connection after this time
keepalive_timeout 10;
# Enable gzip compression
gzip on;
# Allow cross-origin requests when directly accessing Nginx
# If the proxy address already allows cross-origin, these headers are not needed
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
# Configuration for the server module, a sub-module of the http module used to define a virtual host
server {
listen 80;
server_name localhost;
# Root path points to index.html
location / {
root html;
index index.html index.htm;
}
# Requests to localhost/api will be forwarded to 192.168.0.103:8080
location /api {
rewrite ^/b/(.*)$ /$1 break; # Remove the local /api prefix, otherwise a 404 error will occur
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://192.168.0.103:8080; # Forwarding address
}
# Redirect error pages to /50x.html
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
Translation: