I upgraded my Yii2 application version to the latest – 2.0.46 and changed server from apache to Nginx and now I can’t make API GET request from my application using query param auth Given error below
<response>
<name>Unauthorized</name>
<message>Your request was made with invalid credentials.</message>
<code>0</code>
<status>401</status>
<type>yiiwebUnauthorizedHttpException</type>
</response>
My API controller looks like this
public function behaviors(): array
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => CompositeAuth::class,
'authMethods' => [
QueryParamAuth::class,
]
];
$behaviors['language'] = [
'class' => LanguageSelector::class
];
return $behaviors;
}
I read that similar problem people had with apache servers and editing .htaccess helped, but what about Nginx? Or maybe problem is with new Yii2 version!?
API call example that I am making – examplesite/api/controller/method/?access-token=myaccesstoken&id=myID&lang=lv-LV
As my application is using only get requests, old version and new version uses same DB and on old version API call like example given (with good data) works fine. Can enyone help me?
UPDATE: Nginx config
server {
listen 443 ssl;
# server_name exsampleserver;
server_name exampleserverIP
# add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains; preload';
ssl_certificate /etc/nginx/ssl/certdomainexample.crt;
ssl_certificate_key /etc/nginx/ssl/certdomainexample.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
access_log /var/log/nginx/app.log upstream_time;
error_log /var/log/nginx/app-ssl.error.log notice;
root /srv/www/web/frontend/web;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location /api/ {
try_files $uri $uri/ /api/index.php?query_string;
}
location ~ .php$ {
include fastcgi_params;
fastcgi_pass unix:/run/php/php-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_param DOCUMENT_ROOT $realpath_root;
fastcgi_read_timeout 1200;
fastcgi_send_timeout 1200;
fastcgi_connect_timeout 1200;
fastcgi_buffers 4 256k;
fastcgi_busy_buffers_size 256k;
fastcgi_temp_file_write_size 256k;
fastcgi_pass_header Authorization;
}
location ~ /.ht {
deny all;
}
location ~ /.git {
deny all;
}
}
2
Answers
With a help from tech group we founded that working with symlinks in Nginx config $query_params wont work.
So instead of
need to add
into Nginx config
Directory structure:
Nginx config for Yii2 advanced app
This config will allow you to use fallowing domain rules:
Disclaimer
Use this config only in test environments and if you know how nginx works. For production sites better ask for a specialist help.