title: Static file processing meta:

  • name: description content: Swoole static file processing,EasySwoole static file processing
  • name: keywords content: swoole|swoole extension|swoole framework|Swoole static file processing|EasySwoole static file processing

How to handle static resources

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 (!-e $request_filename) {
  9. proxy_pass http://127.0.0.1:9501;
  10. }
  11. }
  12. }

Swoole static file processor

  1. $server->set([
  2. 'document_root' => '/data/webroot/example.com', // V4.4.0 or lower, here must be an absolute path
  3. 'enable_static_handler' => true,
  4. ]);

Swoole comes with its own static file processor. The documentation can be found at https://wiki.swoole.com/wiki/page/783.html

About cross-domain processing

Add the following code in the global event to block all requests to add cross-domain headers

  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. }