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>yii\web\UnauthorizedHttpException</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;
}
}
With a help from tech group we founded that working with symlinks in Nginx config $query_params wont work.
So instead of
location /api/ {
try_files $uri $uri/ /api/index.php?query_string;
}
need to add
location /api/ {
try_files $uri $uri/ /api/index.php$is_args$args;
}
into Nginx config
Directory structure:
examplesite:
- api
+ models
+ controllers
+ web
- backend
+ models
+ controllers
+ web
+ common
+ console
- frontend
+ models
+ controllers
+ web
+ vendor
+ composer.json
Nginx config for Yii2 advanced app
This config will allow you to use fallowing domain rules:
examplesite.test/api - api folder app
examplesite.test/admin - backend folder app
examplesite.test/ - frontend folder app
Disclaimer
Use this config only in test environments and if you know how nginx works. For production sites better ask for a specialist help.
server {
#listen *:443 ssl http2;
listen *:80;
server_name examplesite.test;
#include /etc/nginx/ssl-snippets/ssl-snippet.conf;
# LOGS - config
access_log /var/log/nginx/examplesite.access.log;
error_log /var/log/nginx/examplesite.error.log;
# NGINX - config (sizes, charset, caching, ...)
client_max_body_size 32m;
client_body_buffer_size 32m;
charset utf-8;
gzip on;
gzip_types
text/plain
text/css
text/xml
application/xml
application/xml+rss
text/javascript
application/json
application/x-javascript
application/javascript;
# BASE ROOT DIRECTORY for Yii advanced app setup. Default must be the path to your app composer.json. Let suppose it in /var/www/examplesite
set $base_root /var/www/examplesite;
# BASE PHP-FPM SOKET - this is passed to nginx fastcgi_pass, uncoment or add needed version
set $php_server unix:/run/php/php7.4-fpm.sock;
#set $php_server unix:/run/php/php8.0-fpm.sock;
#set $php_server unix:/run/php/php8.1-fpm.sock;
root $base_root;
index index.php index.html;
# FRONTEND APP - location config
location / {
root $base_root/frontend/web;
try_files $uri $uri/ /frontend/web/index.php$is_args$args;
# omit static files logging, and if they don't exist, avoid processing by Yii (uncomment if necessary)
location ~ ^/.+\.(css|less|js|map|ico|png|jpe?g|gif|webp|svg|eot|ttf|woff|woff2|mp4|mov|swf|txt|pdf)$ {
expires 365d;
log_not_found off;
access_log off;
try_files $uri =404;
}
location ~ ^/assets/.+\.php(/|$) {
deny all;
}
}
# API APP - location config
location /api {
root $base_root/api/web/;
# redirect to the URL without a trailing slash (uncomment if necessary)
#location = /api/ {
# return 301 /api;
#}
location = /api {
try_files $uri /api/web/index.php$is_args$args;
}
# omit static files logging, and if they don't exist, avoid processing by Yii (uncomment if necessary)
location ~ ^/api/.+\.(css|less|js|map|ico|png|jpe?g|gif|webp|svg|eot|ttf|woff|woff2|mp4|mov|swf|txt|pdf)$ {
rewrite ^/api(/.+)$ $1 break;
log_not_found off;
access_log off;
try_files $uri =404;
}
location ~ ^/api/assets/.+\.php(/|$) {
deny all;
}
try_files $uri $uri/ /api/web/index.php$is_args$args;
}
# BACKEND APP - location config
location /admin {
root $base_root/backend/web/;
# redirect to the URL without a trailing slash (uncomment if necessary)
#location = /admin/ {
# return 301 /admin;
#}
# prevent the directory redirect to the URL with a trailing slash
location = /admin {
try_files $uri /backend/web/index.php$is_args$args;
}
# omit static files logging, and if they don't exist, avoid processing by Yii (uncomment if necessary)
location ~ ^/admin/.+\.(css|less|js|map|ico|png|jpe?g|gif|webp|svg|eot|ttf|woff|woff2|mp4|mov|swf|txt|pdf)$ {
rewrite ^/admin(/.+)$ $1 break;
log_not_found off;
access_log off;
try_files $uri =404;
}
location ~ ^/admin/assets/.+\.php(/|$) {
deny all;
}
# if your location is "/backend", try use "/backend/backend/web/index.php$is_args$args"
# bug ticket: https://trac.nginx.org/nginx/ticket/97
try_files $uri $uri/ /backend/web/index.php$is_args$args;
}
# PHP FILES HANDLE
location ~ ^/.+\.php(/|$) {
rewrite (?!^/((frontend|api|backend)/web|api|admin))^ /frontend/web$uri break;
rewrite (?!^/api/web)^/api(/.+)$ /api/web$1 break;
rewrite (?!^/backend/web)^/admin(/.+)$ /backend/web$1 break;
fastcgi_pass $php_server;
fastcgi_split_path_info ^(.+\.php)(.*)$;
include /etc/nginx/fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
try_files $fastcgi_script_name =404;
}
# OTHER LOCATIONS AND RESTRICTIONS
location = /robots.txt { access_log off; log_not_found off; }
location = /favicon.ico { access_log off; log_not_found off; }
location ~* /\. { access_log off; log_not_found off; deny all; }
}
Related
I'm trying to launch my Yii2-advanced project on AWS' Elastic Beanstalk stack running an nginx server. I have been unable figure out a configuration that allows me to access the backend of the site. I have tried extending the nginx configuration via the AWS documentation:
https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/platforms-linux-extend.html
Which does not work. So I modify the configuration manually via vim from the command line.
While using combinations of the following configuration settings:
https://www.yiiframework.com/wiki/799/yii2-app-advanced-on-single-domain-apache-nginx
To no avail. I have tried alias and root for the backend folder and each variation I get either a 404 (file not found) or 502 (bad gateway) error.
At bare minimum, this is what I've tried to add to my nginx configuration:
root /var/www/html/frontend/web;
index index.php index.html index.htm;
location /backend/ {
root ../../backend/web;
}
What am I doing wrong?
Here you can see a fully working yii2 advanced app example nginx configuration. You can change it to match your needs.
App server:
mycoolapp.com
nginx
php7.4-fpm
Routes:
http://mycoolapp.com -- frontend
http://mycoolapp.com/admin -- backend
http://mycoolapp.com/api -- api
Nginx configuration:
server {
## Listen ports config
listen *:80 http2;
#listen *:443 ssl http2;
## Site name config
server_name mycoolapp.com;
## SSL config (uncomment if necessary)
#include /etc/nginx/ssl-snippets/ssl-snippet.conf;
## Access and error log files path
access_log /var/log/nginx/mycoolapp.com.access.log;
error_log /var/log/nginx/mycoolapp.com.error.log;
## Max upload size config
client_max_body_size 32m;
client_body_buffer_size 32m;
charset utf-8;
## Gzip config
gzip on;
gzip_types
text/plain
text/css
application/json
application/x-javascript
text/xml
application/xml
application/xml+rss
text/javascript
application/javascript;
## Path to app root (folder that contains frontend and backend folders)
set $base_root /var/www/html/mycoolapp;
root $base_root;
index index.php index.html;
## Frontend app config
## Entry point: https://mycoolapp.com
location / {
# Path to frontend web folder
root $base_root/frontend/web;
try_files $uri $uri/ /frontend/web/index.php$is_args$args;
## Omit static files logging, and if they don't exist, avoid processing by Yii (uncomment if necessary)
location ~ ^/.+\.(css|less|js|map|ico|png|jpe?g|gif|webp|svg|eot|ttf|woff|woff2|mp4|mov|swf|txt|pdf)$ {
expires 365d;
log_not_found off;
access_log off;
try_files $uri =404;
}
## Deny any php file in assets folder (security)
location ~ ^/assets/.+\.php(/|$) {
deny all;
}
}
## Backend app config
## Entry point: https://mycoolapp.com/admin
location /admin {
## Path to backend web folder
root $base_root/backend/web/;
## Redirect to the URL without a trailing slash (uncomment if necessary)
#location = /admin/ {
# return 301 /admin;
#}
## Prevent the directory redirect to the URL with a trailing slash
location = /admin {
try_files $uri /backend/web/index.php$is_args$args;
}
## Omit static files logging, and if they don't exist, avoid processing by Yii (uncomment if necessary)
location ~ ^/admin/.+\.(css|less|js|map|ico|png|jpe?g|gif|webp|svg|eot|ttf|woff|woff2|mp4|mov|swf|txt|pdf)$ {
rewrite ^/admin(/.+)$ $1 break;
log_not_found off;
access_log off;
try_files $uri =404;
}
## Deny any php file in assets folder (security)
location ~ ^/admin/assets/.+\.php(/|$) {
deny all;
}
try_files $uri $uri/ /backend/web/index.php$is_args$args;
}
## API app config
## Entry point: https://mycoolapp.com/api
location /api {
root $base_root/api/web/;
## Redirect to the URL without a trailing slash (uncomment if necessary)
#location = /api/ {
# return 301 /api;
#}
location = /api {
try_files $uri /api/web/index.php$is_args$args;
}
## Omit static files logging, and if they don't exist, avoid processing by Yii (uncomment if necessary)
location ~ ^/api/.+\.(css|less|js|map|ico|png|jpe?g|gif|webp|svg|eot|ttf|woff|woff2|mp4|mov|swf|txt|pdf)$ {
rewrite ^/api(/.+)$ $1 break;
log_not_found off;
access_log off;
try_files $uri =404;
}
## Deny any php file in assets folder (security)
location ~ ^/api/assets/.+\.php(/|$) {
deny all;
}
try_files $uri $uri/ /api/web/index.php$is_args$args;
}
## PHP configuration
location ~ ^/.+\.php(/|$) {
## Rewrites
rewrite (?!^/((frontend|api|backend)/web|api|admin))^ /frontend/web$uri break;
rewrite (?!^/api/web)^/api(/.+)$ /api/web$1 break;
rewrite (?!^/backend/web)^/admin(/.+)$ /backend/web$1 break;
## FPM config
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(.*)$;
include /etc/nginx/fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
try_files $fastcgi_script_name =404;
}
## Logging and access of restricted folders
location = /robots.txt { access_log off; log_not_found off; }
location = /favicon.ico { access_log off; log_not_found off; }
location ~* /CHANGELOG { access_log off; log_not_found off; deny all; }
location ~* /LICENSE { access_log off; log_not_found off; deny all; }
location ~* /README { access_log off; log_not_found off; deny all; }
location ~* /\. { access_log off; log_not_found off; deny all; }
}
I have a Symfony 2.5.X app running on an nginx server. I will call it domain.com.
The /news URI within that server is configured as a reverse proxy to a remote machine, where I run Wordpress blog on nginx server again. I will call it blog.domain.com.
domain.com's configuration looks like that:
server {
listen 80;
server_name domain.com;
set $project_path /home/webserver/prod.domain.com;
root $project_path/web;
error_log /home/webserver/prod.domain.com/app/logs/nginx_error.log;
access_log /home/webserver/prod.domain.com/app/logs/nginx_access.log;
charset utf-8;
client_max_body_size 65m;
# Some extra speed
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
# Reverse-proxy all /news calls to remote machine
location ~ /news?(.*) {
access_log off;
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_set_header Host blog.domain.com; # without it it doesn't work
#proxy_set_header Host $http_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 http;
proxy_set_header X-Custom-Secret 6ffe3dba7213c678324a101827aa3cf22c;
proxy_redirect off;
proxy_buffering off;
#proxy_intercept_errors on;
proxy_pass http://blog.domain.com:80;
break;
}
# Default URLs
location / {
try_files $uri /app.php$is_args$args;
}
# Error pages (static)
#error_page 403 /errorpages/403.html;
error_page 404 /errorpages/404.html;
#error_page 405 /errorpages/405.html;
error_page 500 501 502 503 504 /errorpages/5xx.html;
# Don't log garbage, add some browser caching
location ~* ^.+\.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
access_log off;
log_not_found off;
expires max;
add_header Pragma "public";
add_header Cache-Control "public, must-revalidate, proxy-revalidate";
try_files $uri /app.php?$query_string;
}
location ~* ^.+\.(css|js)$ {
expires modified +1m;
add_header Pragma "private";
add_header Cache-Control "private";
etag on;
try_files $uri /app.php?$query_string;
}
location = /robots.txt {
allow all;
access_log off;
log_not_found off;
}
# Disallow .htaccess, .htpasswd and .git
location ~ /\.(ht|git) {
deny all;
}
# Parse PHP
location ~ ^/(app|app_dev|config)\.php(/|$) {
include fastcgi_params;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param HTTPS off;
fastcgi_pass php;
}
}
blog.domain.com's configuration looks like that:
server {
listen 80;
server_name blog.domain.com;
root /home/webserver-blog/news;
access_log /home/webserver-blog/logs/http_access.log;
error_log /home/webserver-blog/logs/http_error.log;
charset utf-8;
client_max_body_size 65m;
# Some extra speed
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
# Default URLs
location / {
# This never gets parsed as / is reserved for our main server
}
location ~* ^/news/(wp-content|wp-admin) { # without this directive I didn't have any static files
root /home/webserver-topblog/;
}
location ~* ^/news {
try_files $uri $uri/ /index.php?args;
}
# Don't log garbage
location ~* ^.+\.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
access_log off;
log_not_found off;
expires max;
}
location = /robots.txt {
allow all;
access_log off;
log_not_found off;
}
# Disallow .htaccess or .htpasswd
location ~ /\.ht {
deny all;
}
# Disallow logs
location ~ ^/logs/.*\.(log|txt)$ {
deny all;
}
# Parse PHP
location ~ \.php$ {
#if (!-e $request_filename) { rewrite / /index.php last; }
try_files $uri =404;
include fastcgi_params;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass php;
}
}
As you can figure out, my Wordpress resides in /home/webserver-blog/news/. I have a slightly modified index.php file in Wordpress that checks for X-Custom-Secret header, and if it's not present (or invalid), it forces a 301 redirection to domain.com/news/
Now I have tried several different approaches to get it running properly.
First (and most obvious) was pointing the root of blog.domain.com's to /home/webserver-blog/ and allowing nginx to naturally pass the request URI to the subdirectory, /news. This worked quite well, yet it didn't allow me to utilize Wordpress' permalinks and just worked with query strings. Other strange behaviour it produced was actually exposing blog.domain.com in HTTP redirect if you called /news without trailing slash. Those redirects were quickly handled by my custom index.php, but still I want to avoid exposing blog.domain.com completely.
Second (and pretty-much current) approach was again pointing the root of blog.domain.com's directly to Wordpress' directory, /home/webserver-blog/news/ and cheating all the requests for static files with location ~* ^/news/(wp-content|wp-admin) directive pointing it's root directory one levelel up. This worked for both permalinks and static files, but again - /news/wp-login.php gives me infinite redirects to itself, and /news/wp-admin/ actually downloads the index.php file instead of parsing it (sends it as application/octet-stream)
I am completely out of ideas... Any help would be much appreciated.
I think I managed to come with a so-so solution. Far from being perfect or clean, but... well, it works.
blog.domain.com's config:
server {
listen 80;
server_name blog.domain.com;
root /home/webserver-blog;
access_log /home/webserver-blog/logs/http_access.log;
error_log /home/webserver-blog/logs/http_error.log;
charset utf-8;
client_max_body_size 65m;
# Some extra speed
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
# Default URLs
location ~* ^/news$ {
rewrite ^ $scheme://domain.com/news/ permanent; # ** HARDCODED production url
break;
}
location / {
try_files $uri $uri/ #redir;
}
location #redir {
rewrite ^/news/(.*)$ /news/index.php?$1 last;
}
# Don't log garbage
location ~* ^.+\.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
access_log off;
log_not_found off;
expires max;
}
location = /robots.txt {
allow all;
access_log off;
log_not_found off;
}
# Disallow .htaccess or .htpasswd
location ~ /\.ht {
deny all;
}
# Disallow logs
location ~ ^/logs/.*\.(log|txt)$ {
deny all;
}
# Parse PHP
location ~ \.php$ {
include fastcgi_params;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param HTTPS off;
fastcgi_pass php;
}
}
So the trick is I'm still operating on filesystem directories and not fancy all-the-way-around rewrites and redirects. news/ still remains a physical directory in the filesystem that gets read with the location / directive from nginx. Previous issues with exposing the blog.domain.com domain on trying to access without slashes seem to be native nginx's behaviour - it sees a directory, it adds a slash at the end; and since it's server_name is set to blog.domain.com, here we go. Hardcoding production URL and putting that rule on top pretty much fixed the problem.
#redir location again enabled the Wordpress' permalinks nicely.
One more thing I have added to entire setup to prevent people form going directly on http://blog.domain.com/ is another index.php file stored directly in /home/webserver-blog/:
<?php
/*
* domain.com redirector
*/
$production = 'http://domain.com/news/';
// Redirect nicely
if(isset($_SERVER['REQUEST_URI']) and $_SERVER['REQUEST_URI'] !== '/') {
$target = sprintf('%s%s', $production, preg_replace('/^\//', null, $_SERVER['REQUEST_URI']));
header('Location: ' . $target);
}
else header('Location: ' . $production);
...and, as mentioned before, few lines on top of Wordpress' original index.php:
<?php
/*
* wordpress loader
*/
$production = 'http://domain.com/news/';
// Allow only reverse-proxied requests
if(!isset($_SERVER['HTTP_X_CUSTOM_SECRET']) or $_SERVER['HTTP_X_CUSTOM_SECRET'] !== md5('your-md5encoded-text-in-proxy_set_header-X-Custom-Secret')) {
die(header('Location: ' . $production));
}
require_once dirname(__FILE__) . '/index-wp-org.php';
Ugly... but works.
I'd still be happy to hear nicer solutons. :)
Images are only displaying if they have the correct case. These need to be case insensitive please see my config file.
The image I have having trouble with works at:
http://domain.com/sites/default/files/vimages/imagename.jpg
but not at
http://domain.com/sites/default/files/vimages/imagename.JPG
server {
listen 80;
server_name domain.com;
root /home/domain.com/www; ## <-- Your only path reference.
access_log /home/domain.com/logs/access.log;
error_log /home/domain.com/logs/error.log;
# Enable compression, this will help if you have for instance advagg‎ module
# by serving Gzip versions of the files.
gzip_static on;
gzip on;
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
# This matters if you use drush
location = /backup {
deny all;
}
# Very rarely should these ever be accessed outside of your lan
location ~* \.(txt|log)$ {
allow 192.168.0.0/16;
deny all;
}
location ~ \..*/.*\.php$ {
return 403;
}
# No no for private
location ~ ^/sites/.*/private/ {
return 403;
}
# Block access to "hidden" files and directories whose names begin with a
# period. This includes directories used by version control systems such
# as Subversion or Git to store control files.
location ~ (^|/)\. {
return 403;
}
location / {
# This is cool because no php is touched for static content
try_files $uri #rewrite;
}
location #rewrite {
# Some modules enforce no slash (/) at the end of the URL
# Else this rewrite block wouldn't be needed (GlobalRedirect)
rewrite ^ /index.php;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
#fastcgi_pass 127.0.0.1:9000;
fastcgi_read_timeout 180;
fastcgi_intercept_errors on;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires 52w;
add_header Cache-Control "max-age=31449600, no-transform, public";
log_not_found off;
}
# Catch image styles for D7 too.
location ~* ^/sites/.*/files/styles/ {
try_files $uri #rewrite;
}
location ~* /sites/.*/files/vimages/ {
try_files $uri #rewrite;
}
# Fighting with ImageCache? This little gem is amazing.
location ~ ^/sites/.*/files/imagecache/ {
try_files $uri #rewrite;
}
}
Nginx is working against the filesystem and has no control over the name of the files when serving from a directory.
If you want case insensitive you need to do a rewrite.
I have a Magento shop at http://example.com and I want to keep a Wordpress blog at http://example.com/blog.
I have installed the blog and everything seems to be fine but when am logging to Wp-Admin am getting 404 for css and js files due to which dashboard is looking very ugly.
Am I doing any mistake? am attaching my nginx config file
##################################################################################
#
# example.com
#
##################################################################################
server {
listen 80;
server_name example.com ;
#charset koi8-r;
#access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
location / {
root /usr/share/nginx/html/mebozo-magento.mebozo.com;
try_files $uri $uri/ #handler; ## If missing pass the URI to Magento's front handler
index index.php index.html index.htm;
}
location /blog {
root /usr/share/nginx/html/mebozo-magento.mebozo.com/blog;
try_files $uri $uri/ /blog/index.php;
index index.php index.html index.htm;
rewrite ^.*/files/(.*) /wp-includes/ms-files.php?file=$2;
rewrite ^.*/wp-admin(.*) $1wp-admin/;
}
location ~* ^.+\.(html|jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js)$
{
root /usr/share/nginx/html/mebozo-magento.mebozo.com/blog;
rewrite ^/.*(/.*\.(html|jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js))$ $1 last;
rewrite ^.*/files/(/.*(html|jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js))$/wp-includes/ms-files.php?file=$1 last;
expires 30d;
break;
}
## These locations would be hidden by .htaccess normally
#location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
#expires 1y;
#log_not_found off;
#}
location ~ .php/ {
## Forward paths like /js/index.php/x.js to relevant handler
rewrite ^(.*.php)/ $1 last;
}
################For Foomen Speedster###############
#rewrite ^/minify/([0-9]+)(/.*.(js|css))$ /lib/minify/m.php?f=$2&d=$1 last;
# rewrite ^/skin/m/([0-9]+)(/.*.(js|css))$ /lib/minify/m.php?f=$2&d=$1 last;
# location /lib/minify/ {
# allow all;
# }
error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
}
#############gzip###########
gzip on; # use gzip compression
gzip_min_length 1100;
gzip_buffers 4 8k;
gzip_proxied any; # enable proxy for the fcgi requests
gzip_types text/plain text/css application/x-javascript text/javascript application/json;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
location #handler { ## Magento uses a common front handler
rewrite / /index.php;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
# if (!-e $request_filename) { rewrite / /index.php last; } ## Catch 404s that try_files miss
root /usr/share/nginx/html/mebozo-magento.mebozo.com;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html/mebozo-magento.mebozo.com$fastcgi_script_name;
include fastcgi_params;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
location ~ /\.ht {
deny all;
}
}
I will attempt to solve this puzzle by suggesting that we clean up your nginx config file. Your */files/ rewrites look to be problematic to me.
Without knowing what your nginx.conf file looks like OR what your http {block} looks like, I will assume that it is pretty clean and that you are handling your global settings like gzip types, ssl protocols and ciphers, and additional headers, etc. there. I know that you included your gzip on in your file but sometimes duplicate that in server not realizing it is already set a layer above... if not add your gzip back in as necessary. All that said, after reading your conf file completely and I would suggest rewriting it to something like this:
(Note: the new URI level location and the #rewrites, and the removal of redundant root path definitions.)
server {
listen 80;
listen [::]:80;
## SSL CONFIGURATION (can be done here in same file)
#listen 443 ssl http2;
#listen [::]:443 ssl http2;
#ssl_certificate /etc/nginx/ssl/cert_chain.crt;
#ssl_certificate_key /etc/nginx/ssl/star_example.com.priv.key;
# domain name
server_name example.com www.example.com;
# doc root
root /usr/share/nginx/html/mebozo-magento.mebozo.com;
## Logs per vhost
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log warn;
## This can also be set in your http block and if it is, it's not needed here.
index index.php index.html index.htm;
# Adjust upload max file size settings
# This value should match your PHP.ini config settings for upload_max_filesize
client_max_body_size 50M; # allows file uploads up to 50 megabytes
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
## Main Magento location
location / {
try_files $uri $uri/ #rewrite;
}
# Your blog location
location /blog/ {
try_files $uri $uri/ #rewrite_blog;
}
# redirect server error pages to the static page /50x.html
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx;
}
## These locations are protected
location ~ /(app|downloader|includes|pkginfo|var|errors/local.xml)/ {
deny all;
}
## Images
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires max;
log_not_found off;
access_log off;
add_header ETag "";
}
location =/js/index.php/x.js {
rewrite ^(.*\.php)/ $1 last;
}
# rewrites
location #rewrite {
rewrite / /index.php?$args;
}
location #rewrite_blog {
rewrite /blog/ /blog/index.php?$args;
}
## Execute PHP scripts
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
## Store code with multi store/domain magento instance
#fastcgi_param MAGE_RUN_CODE $mage_code;
#fastcgi_param MAGE_RUN_TYPE $mage_type;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# Banned locations (only reached if the earlier PHP entry point regexes don't match)
location ~* (\.php$|\.sh$|\.txt$|\.htaccess$|\.git|\.sample$|mage$) {
deny all;
}
}
What would be the nginx rewrite rule to redirect my wordpress permalink structure from /%category%/%postname%/ to /%postname%/?
In summary, you need to let NGINX know that if that file doesn't exist, to not throw a 404 error, but rather call index.php. Wordpress is smart enough to parse the URL as parameters, and serve the correct page.
Add this snippet in your server configuration block:
location / {
try_files $uri $uri/ /index.php?$args;
}
Here is a complete example from nginx.org:
# Upstream to abstract backend connection(s) for php
upstream php {
server unix:/tmp/php-cgi.socket;
server 127.0.0.1:9000;
}
server {
## Your website name goes here.
server_name domain.tld;
## Your only path reference.
root /var/www/wordpress;
## This should be in your http block and if it is, it's not needed here.
index index.php;
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
location / {
# This is cool because no php is touched for static content.
# include the "?$args" part so non-default permalinks doesn't break when using query string
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
#NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
include fastcgi.conf;
fastcgi_intercept_errors on;
fastcgi_pass php;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires max;
log_not_found off;
}
}