Nginx

配置 NGINX:用於帶有 nextjs 的 Wordpress Headless

  • February 18, 2022

我想製作一個 WordPress Headless(在 /graphql uri 上使用 wpgraphql API),其中前端將是 next.js。我希望前端(Next.js)和後端(WordPress.admin、content 和 API)都在同一個域中

為此,我希望所有的請求都只針對 WordPress/wp-admin/*並且被定向到 WordPress /wp-content/*/graphql所有其他 uri 將通過反向代理重定向到 localhost:3000 中的 next.js 伺服器。下面是 nginx 配置文件。

server {
 listen 80;
 listen [::]:80;
 root /var/www/wordpress;
 index index.php index.html index.htm;
 server_name localhost;

 client_max_body_size 100M;
 autoindex off;

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

 location ~ \.php$ {
   include snippets/fastcgi-php.conf;
   fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
   fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
   include fastcgi_params;
 }

 # Next.js
 location # ... {
   proxy_pass http://localhost:3000;
   proxy_http_version 1.1;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection "upgrade";
   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_set_header X-Forwarded-Proto $scheme;
   proxy_set_header X-Forwarded-Host $host;
   proxy_set_header X-Forwarded-Port $server_port;
 }
}

任何幫助表示讚賞,謝謝

nginx 使用location指令指定的最長匹配前綴。因此,以下設置應該可以滿足您的需求。

您可以採取以下方法:

 location /wp-admin {
    try_files $uri $uri/ /index.php?$args;
 }
 
 location /wp-includes {
    try_files $uri $uri/ /index.php?$args;
 }
   
 location /wp-json {
    try_files $uri $uri/ /index.php?$args;
 }

 location /wp-content {
     try_files $uri $uri/ /index.php?$args;
 }

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

引用自:https://serverfault.com/questions/1093728