如何处理静态资源

Apache URl rewrite

  1. <IfModule mod_rewrite.c>
  2. Options +FollowSymlinks
  3. RewriteEngine On
  4. RewriteCond %{REQUEST_FILENAME} !-d
  5. RewriteCond %{REQUEST_FILENAME} !-f
  6. #RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L] fcgi下无效
  7. RewriteRule ^(.*)$ http://127.0.0.1:9501/$1 [QSA,P,L]
  8. #请开启 proxy_mod proxy_http_mod request_mod
  9. </IfModule>

Nginx URl rewrite

  1. server {
  2. root /data/wwwroot/;
  3. server_name local.swoole.com;
  4. location / {
  5. proxy_http_version 1.1;
  6. proxy_set_header Connection "keep-alive";
  7. proxy_set_header X-Real-IP $remote_addr;
  8. if (!-f $request_filename) {
  9. proxy_pass http://127.0.0.1:9501;
  10. }
  11. }
  12. }

Swoole静态文件处理器

  1. $server->set([
  2. 'document_root' => '/data/webroot/example.com', // v4.4.0以下版本, 此处必须为绝对路径
  3. 'enable_static_handler' => true,
  4. ]);

Swoole 有自带的静态文件处理器。文档请见 https://wiki.swoole.com/wiki/page/783.html

关于跨域处理

在全局事件添加以下代码 拦截所有请求添加跨域头

  1. public static function onRequest(Request $request, Response $response): bool
  2. {
  3. // TODO: Implement onRequest() method.
  4. $response->withHeader('Access-Control-Allow-Origin', '*');
  5. $response->withHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
  6. $response->withHeader('Access-Control-Allow-Credentials', 'true');
  7. $response->withHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
  8. if ($request->getMethod() === 'OPTIONS') {
  9. $response->withStatus(Status::CODE_OK);
  10. return false;
  11. }
  12. return true;
  13. }