TLDR: 我在使用Material-UI(服务器端渲染)和Nginx(使用反向代理)为NextJS设置CSP时遇到了麻烦。
目前我遇到了加载Material-UI样式表和加载自己的样式的问题。
使用@material-ui/core/styles
中的makeStyles
注意:
- 参考https://material-ui.com/styles/advanced/#next-js以启用SSR
- 我查看了https://material-ui.com/styles/advanced/#how-does-one-implement-csp但不确定如何让nginx遵循
nonce
值,因为nonce是作为不可预测的字符串生成的。
default.conf (nginx)
# https://www.acunetix.com/blog/web-security-zone/hardening-nginx/
upstream nextjs_upstream {
server localhost:3000;
# We could add additional servers here for load-balancing
}
server {
listen $PORT default_server;
# redirect http to https. use only in production
# if ($http_x_forwarded_proto != 'https') {
# rewrite ^(.*) https://$host$request_uri redirect;
# }
server_name _;
server_tokens off;
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;
# hide how is app powered. In this case hide NextJS is running behind the scenes.
proxy_hide_header X-Powered-By;
# set client request body buffer size to 1k. Usually 8k
client_body_buffer_size 1k;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;
# ONLY respond to requests from HTTPS
add_header Strict-Transport-Security "max-age=31536000; includeSubdomains; preload";
# to prevent click-jacking
add_header X-Frame-Options "DENY";
# don't load scripts or CSS if their MIME type as indicated by the server is incorrect
add_header X-Content-Type-Options nosniff;
add_header 'Referrer-Policy' 'no-referrer';
# Content Security Policy (CSP) and X-XSS-Protection (XSS)
add_header Content-Security-Policy "default-src 'none'; script-src 'self'; object-src 'none'; style-src 'self' https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap ; form-action 'none'; frame-ancestors 'none'; base-uri 'none';" always;
add_header X-XSS-Protection "1; mode=block";
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
location / {
# limit request types to HTTP GET
# ignore everything else
limit_except GET { deny all; }
proxy_pass http://nextjs_upstream;
}
}