Git Product home page Git Product logo

rocket-nginx's Introduction

Rocket-Nginx

Rocket-Nginx is a Nginx configuration for the WordPress cache plugin WP Rocket. It enables Nginx to serve directly previously cached files without calling WordPress or any PHP. It also adds headers to cache CSS, JS and medias in order to leverage browser's cache by reducing request to your web server.

You might ask yourself: "How good is this configuration?".

Let's just say that WP Rocket themselves use it on their website to make it even faster!

This project is sponsored by SatelliteWP, a WordPress maintenance service located near Montreal, Canada. Our service is offered in both English and French. SatelliteWP fait de l'entretien de sites WordPress.

SatelliteWP - WordPress Maintenance

  1. Contributors
  2. Before You Start
  3. Installation
  4. Configuration
  5. Debug
  6. Limitations
  7. FAQ
  8. License

The configuration was created by Maxime Jobin (@maximejobin) and is now maintained by SatelliteWP.

As the configuration's goal is to serve cached files directly without having to execute any PHP from WordPress, this may cause your scheduled jobs to not be called. As you may already know, WP-Cron jobs are not real cron jobs and are executed only when you have visits on your site.

In order to make sure your scheduled tasks run when they should, it is strongly suggested to disable WordPress cron jobs and create a real cron job.

To disable WordPress cron job, add the following line to your wp-config.php:

define( 'DISABLE_WP_CRON', true );

Then, manually a cron job every 15 minutes (it should be enough for most websites):

*/15 * * * * wget -q -O - http://www.website.com/wp-cron.php?doing_wp_cron &>/dev/null

or

*/15 * * * * curl http://www.website.com/wp-cron.php?doing_wp_cron &>/dev/null

or

*/15 * * * * cd /home/user/public_html; php wp-cron.php &>/dev/null

Make sure you test that your tasks still run after this change!

To use the script, you must include it in your actual configuration. If your WordPress website is not yet configured to run with Nginx, you can check the Nginx configuration for WordPress documentation.

Only one instance of Rocket-Nginx is needed for all your WordPress websites using WP Rocket. You can generate as many configuration files as needed.

You can create a folder rocket-nginx directory in your Nginx configuration directory. If you are using Ubuntu, your Nginx configuration (nginx.conf) should be found in: /etc/nginx/.

To install, you can:

cd /etc/nginx
git clone https://github.com/satellitewp/rocket-nginx.git

Since version 2.0, the configuration must be generated. To generate the default configuration, you must rename the disabled ini file and run the configuration parser:

cd rocket-nginx
cp rocket-nginx.ini.disabled rocket-nginx.ini
php rocket-parser.php

This will generate the default.conf configuration that can be included for all websites. If you need to alter the default configuration, you can edit the ini file and add another section at the bottom of the file.

Then, in your Nginx configuration file, you must include the generated configuration. If your websites configurations are in /etc/nginx/sites-available, you need to alter your configuration:

server {
  ...
  
  # Rocket-Nginx configuration
  include rocket-nginx/conf.d/default.conf;
  
  ...
}

Before you reload your configuration, make sure you test it: nginx -t

Once your test is done, you must reload your configuration. service nginx reload

That's it.

There is no configuration to do. It will work out of the box. But, you can edit a couple of things...

Just open the rocket-nginx.ini file and see all the options in it.

You can add a new section based on the default configuration like this:

# This creates the new section and will generate a new configuration
[example.com : default]

# This will add a value to invalidate the cache with a cookie
cookie_invalidate[] = "my_custom_cookie"

Once you edit the ini file, you must regenerate your Nginx configuration file by running the parser:

php rocket-parser.php

Then, newly added or modified sections will generate update configuration file (*.conf).

Finally, each time you generate (or regenerate) the configurations files, you have to:

  1. Test it to make sure it did not produce any error:

    nginx -t

  2. Reload the configuration:

    service nginx reload

Starting at version 3.0, a conf.dfolder is created. For each different profile you create, a subfolder is created inside that folder. In it, you can create files that will be included within the generated configuration file.

You can include configuration files at different times.

Before Rocket-Nginx starts

In the default profile, create a file in the conf.d/default/ having the following filename pattern : start.*.conf.

Globally in every section

In the default profile, create a file in the conf.d/default/ having the following filename pattern : global.*.conf.

In the HTTP section

In the default profile, create a file in the conf.d/default/ having the following filename pattern : http.*.conf.

Preprocess (after all variables to use are set)

In the default profile, create a file in the conf.d/default/ having the following filename pattern : preprocess.*.conf.

In the CSS section

In the default profile, create a file in the conf.d/default/ having the following filename pattern : css.*.conf.

In the JS section

In the default profile, create a file in the conf.d/default/ having the following filename pattern : js.*.conf.

In the Media section

In the default profile, create a file in the conf.d/default/ having the following filename pattern : media.*.conf.

You may want to check if your files are served directly by Nginx and not calling any PHP. To do that, open the rocket-nginx.ini file and change the debug value from:

debug = false

To:

debug = true

The following header is present no matter if debug is set to true or false:

  • X-Rocket-Nginx-Serving-Static: Did the configuration served the cached file directly : HIT, MISS, BYPASS. This will add the following headers to your response request:
  • X-Rocket-Nginx-Reason: If serving static is not set to "HIT", what is the reason for calling WordPress. If "HIT", what is the file used (URL).
  • X-Rocket-Nginx-File: If "HIT", what is the file used (path on disk).
  • X-Rocket-Nginx-Device: What device was used to call the server ("desktop" or "mobile").

Reasons for not serving a cached file:

  • Post request: The request to the web server was a POST. That means data was sent and the answer may need to be different from the cached file (e.g. when a comment is sent).
  • Arguments found: One or more argument was found in the request (e.g. ?page=2).
  • Maintenance mode: The .maintenance file was found. Therefore, let's WordPress handle what should be displayed.
  • Cookie: A specific cookie was found and tells to not serve the cached page (e.g. user is logged in, post with password).
  • Specific mobile cache activated: If you activated specific cache (one for mobile and one for desktop) in WP Rocket, HTML files (pages, posts, ...) won't be served directly because Rocket-Nginx cannot know if the request was made by mobile or desktop device.
  • File not cached: No cached file was found for that request.

Is Rocket-Nginx perfect? No, it's not! We tried to make it as perfect as possible, but Nginx's scripting language does not offer all possibilities offered by a language like PHP, for instance. Therefore, there are some limitations.

Encoded slugs

Short answer: An encoded slug cannot be served by Rocket-Nginx.

Due to Nginx's scripting limitations, slugs like 'جزازة العشب' are encoded and the file is stored by WP Rocket as '%d8%ac%d8%b2%d8%a7%d8%b2%d8%a9%20%d8%a7%d9%84%d8%b9%d8%b4%d8%a8' (lowercase). Some browsers, like Google Chrome, will send the request as '%D8%AC%D8%B2%D8%A7%D8%B2%D8%A9%20%D8%A7%D9%84%D8%B9%D8%B4%D8%A8' (uppercase). Using a language like PHP, it would be easy to compare these strings as equal. With Nginx, this is not possible unless a third party module (like Perl or Lua) is needed. To make Rocket-Nginx as generic as possible, it was decided to not add a module dependency. If you want to support encoded slugs and add the missing code, note that version 3.1.0 (and later) offers a new configuration include named "preprocess" to modify the $rocket_uri_path variable case (force lowercase).

WEBP Compatibility

Short answer: Rocket-Nginx won't serve the WebP caching files generated by WP Rocket if you activate the WebP Compatibility feature.

WP Rocket is able to create a specific cache if you used a tool to convert your images (JPG, PNG, ...) to WebP. Unfortunately, the Nginx's scripting language is not powerful enough to achieve the validation correctly. Therefore, if you activate this feature, Rocket-Nginx will let WP Rocket handle the request and serve the right cached page, depending on the context.

Is Rocket-Nginx compatible with BF Cache (Back/forward cache)?

Yes! If your website does not display sensitive data and is a good match for Back/forward caching, you must must edit your Rocket-Nginx configuration by following the BF Cache discussion in the issues.

How do I upgrade from version 1 or 2 to version 3?

We suggest that you save your previous configuration and start over. Take this opportunity to review everything as many things have changed. Officially, version 3.x is not backward-compatible with previous versions. Starting from scratch should not take more than 15 minutes.

What is new in version 3.x?

Many things!

  • Query strings to cache are supported via the ini file. See the WP Rocket Cache query strings documentation for configuration.
  • Query string to ignore are supported. See the WP Rocket Cache query strings to ignore documentation for configuration.
  • Default HSTS value was removed.
  • Custom configurations can be included in every sections
  • Custom expiration are supported for CSS, JS and medias
  • Allowing adding headers from the config file was removed.

Do you have any benchmark about the project ?

No. People love benchmark as much as they hate them. All benchmarks have people claiming that X or Y or Z could have been done to improve the outcome. In this project, the benchmark would depend on how many plugins you have that are affecting the page even if the output is in cache (e.g. WP Rocket executes PHP even when a file is in cache). What we can say though is that you will go from NGINX → PHP-FPM → WordPress (PHP and Database) → Static file to NGINX → Static file. In other words, you are serving the static file directly from NGINX instead of passing the request to FPM then to PHP (for WP Rocket... at least) before serving the static file.

Will Rocket-Nginx work if my website uses a SSL certificate (https) ?

Yes! Rocket-Nginx will detect if the request was made through HTTP or HTTPS and serve the right file depending on the request type. Both protocols are handled automagically since version 1.0.

Released under the MIT License. See the license file for details.

rocket-nginx's People

Contributors

j-allard-22 avatar mathieu-aubin avatar maximejobin avatar tcg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rocket-nginx's Issues

Chrome downloads gzip compressed file when served by rocket-nginx

After enabling rocket-nginx, static gzip compressed files are served as downloads instead of displaying the page in the browser.

I can not figure out why.

I am using a reverse proxy in front of the nginx server with rocket-nginx enabled,

These are the headers received for the cached file.

accept-ranges:bytes

cf-ray:32d01df8b815514c-SJC

content-length:40089

content-type:application/octet-stream

date:Mon, 06 Feb 2017 16:53:13 GMT

etag:"5898a388-9c99"

last-modified:Mon, 06 Feb 2017 16:25:44 GMT

server:cloudflare-nginx

status:200

x-rocket-nginx-bypass:Yes

Multiple Slashes - Nginx Not Cached

I have enabled debug mode and for some reason files are not cached in Nginx and I can see in debug headers multiple slashes //.. why is this happening ?

x-rocket-nginx-bypass Yes
x-rocket-nginx-file /var/www/html/wp-content/cache/wp-rocket/www.domain.com///index-https.html_gzip
x-rocket-nginx-reason /wp-content/cache/wp-rocket/www.domain.com///index-https.html_gzip

x-rocket-nginx-bypass:No

I have such stack:
debian8+nginx+mariadb+opcache+memcached and wprocket

i have insalled rocket-nginx debug show me:
x-rocket-nginx-bypass:No
x-rocket-nginx-file:/usr/share/nginx/html/ciplenok.com/wp-content/cache/wp-rocket/ciplenok.com//wp-content/themes/flatastic/js/jquery.raty.min.js/index-https.html_gzip ( and others files)
x-rocket-nginx-reason:File not cached

my site: ciplenok.com

What am i suppose to do to enable your plugin?

Checking for user-defined cookies

Hi there,

I'm trying to set a cookie under "Advanced Settings" -> "Don't cache pages that use the following cookies" . But it looks like this configuration does not take that into account, and the pages are cached nonetheless.

Is there a way to fix this?

CORS header ‘Access-Control-Allow-Origin’ missing).

Hi,

Does your config overwrite any header rules I have setup in my original configuration?

I have set inside: etc/nginx/sites-enabled/default


location ~ .(ttf|ttc|otf|eot|woff|woff2|font.css|css|js)$ {
add_header Access-Control-Allow-Origin "*";
}

I am receiving this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.cloudfront.net/fonts/didot-24b-webfont.woff2. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Also when doing curl -I

I cannot see the access-control-allow-origin header... I only see X-rocket headers..

many thanks

Issue with WordPress Multisite in Directory mode...

Great directive, thanks for your hard work on this!

There seems to be an issue where the cached file retrieval is incomplete for Directory sites in a Multisite environment. I can't see why because these appear like regular folders in wp-content/cache/wp-rocket/ so you would think they are handled the same way. I know I had to set WP Rocket up for each site. Maybe a permalink type confusion?

Your directive works fine for the root site. It works fine for subdomains in multisite. But when we try it on Directory sites in Multisite, it loads parts of the pages.

Any insight is greatly appreciated. Let me know if there's anything I can do to help identify the problem.

"server" directive is not allowed here

Hi!
Could someone please explain this part to me? Idk what to do...

My sites are under: /etc/nginx-sp/vhosts.d/
and for each site i have domain.conf and domain.d
and under each domain.d i have one file called main.conf

and my installation is under /etc/nginx-sp/rocket-config
including the file rocket-nginx (without any extension name)

But idk what to do next :S

Edit: Ive come a bit on the way, but now i get this error:
"server" directive is not allowed here in /etc/nginx-sp/vhosts.d/domain.d/main.conf:1

Then, in your configuration file, you must include the configuration. If your websites configurations are in /etc/nginx/sites-available, you need to alter your configuration:

server {
  ...

  # Rocket-Nginx configuration
  include rocket-nginx/rocket-nginx.conf;

  ...
}

> 

Nginx as reverse proxy and rocket-nginx

Hello Maxime,

Thanks very much for your code. It is in production with woocommerce and give to our shop the speed of a static website.

If I work with hiawatha web server for security purpose, this one can't serve directly files in wp-rocket cache folder without calling php-fpm process.
Same scenario with apache or other web server.

So, is it possible to use your script with nginx as reverse proxy ?

Best regards

Rocket-Nginx serves a file that should not be cached

In the Advanced Options, you can set Never cache the following pages which means WP-Rocket will not serve a cached version of the page.

The problem is that WP-Rocket creates the file on the disk even if you add pages in this option. It looks like the plugin validates if the cached version "should" be served in the plugin code.

The suggestion would be for WP-Rocket to NOT write the file on the disk. Otherwise, Rocket-Nginx thinks, as a cached file was created, that it should be served.

A ticket was opened with WP-Rocket and I am waiting for a response about the issue.

Cache Bypass Reason Rocket Cache

Am I missing something, but should this not have hit the nginx cache?
It appears that it is bypassing the cache and just using the standard WP-Rocket cache.

X-Rocket-Nginx-Bypass:Yes
X-Rocket-Nginx-File:/var/www/example.com/htdocs/wp-content/cache/wp-rocket/www.example.com///index.html_gzip
X-Rocket-Nginx-Reason:/wp-content/cache/wp-rocket/www.example.com///index.html_gzip

I am using EasyEngine and this is my site-available/example.com call of the rocket-nginx files.

server {

  # Rocket-Nginx configuration
  include rocket-nginx/rocket-nginx.conf;

    server_name example.com   www.example.com;

I am sure I am missing something as to why this is not hitting the cache.

Rocket NGINX fixes Expires: max issues, however, files are still showing "File not cached"

HTTP/1.1 304 Not Modified
Server: nginx
Date: Mon, 11 Jul 2016 18:27:20 GMT
Last-Modified: Wed, 06 Jul 2016 21:17:06 GMT
Connection: keep-alive
ETag: "577d7552-162b"
Expires: Thu, 31 Dec 2037 23:55:55 GMT
Cache-Control: max-age=315360000
X-Rocket-Nginx-Bypass: No
X-Rocket-Nginx-Reason: File not cached
X-Rocket-Nginx-File: /home/theupbeatk9/public_html/wp-content/cache/wp-rocket/theupbeatk9.com//wp-content/uploads/2016/06/upbeat-k9-logo.png/index-https.html_gzip
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
X-Xss-Protection: 1; mode=block

Using Rocket-Nginx w/ nDeploy on CentOS & cPanel/WHM Server

Hello,

I have a few sites that are using Nginx w/ PHP-FPM & WordPress w/ WP-Rocket's plugin installed. I'm on a CentOS 6 server using nDeploy (see links below) which handles my NGINX & PHP-FPM installation & basic configurations.

I'm trying to figure out how to configure this to work in this setup, however, I'm having some trouble when adding to my nginx.conf file.

Can you please take a look at how nDeploy works and see if you can please help me out?

Thanks!

https://support.sysally.net/projects/ndeploy/wiki
https://github.com/AnoopAlias/nDeploy

Purging Nginx Files

Hi,

Could you please tell me where nginx stores cached files?

It appears that even if I clear the WP-Rocket cache several times, nginx still stores older versions?

many thanks

Different wp-content file in each file

Hi. Thanks for the contribution.
I recently changed server and move to nginx server.
The problem now is that wp-rocket not working fine. I have already included your configuration into my server. But today I noticed that you are using the default wp-content path for serving the requests.
Is there a way to dynamic configure it for each site or now I have to include your code in every site's nginx conf separately?

Lot of 404 on generated JS / CSS Files

Hi Maxime,

I moved from apache to nginx,
Everything is working fine when i'm browsing the website on my side (and on different devices) everything is correctly loaded but on my error log i have a lot of 404 errors on js and css generated by wp-rocket in the /wp-content/cache/min/1/.
No 404 errors on other files (videos, images).
Thoses 404 errors are generated by other visits. The problem is not for everyone cause 95% of the request on the access log are fine.

I can't figure out where thoses errors come from :(

Can it be the browser cache of the client ? Do you have an idea how i can fix that ? I was having no problem on apache.

Thank you very much !

Mobile Detection Issue

Hi Maxime,
I have issue with mobile content, temporarily I have to set $rocket_bypass from 1 to 0, otherwise mobile user will be serve by desktop content.

Nginx error log

Hey,

Something like this should be good (although I would first contact hosting provider):

/**********************************************

Hi Maxime,

I have one issue with my NGINX configuration. I am using WP Rocket and have implemented your settings. However I am getting the following errors in NGINX error log:

=========== error message ===========
2016/07/21 05:23:23 [warn] 21835#21835: *983 using uninitialized "rocket_file" variable, client: 52.1.31.247, server: appleme.club, request: "GET /feed/ HTTP/1.1″, host: "appleme.club"
2016/07/21 05:28:07 [warn] 21835#21835: *1100 using uninitialized "rocket_is_bypassed" variable, client: 195.2.219.97, server: appleme.club, request: "GET /feed/ HTTP/1.1″, host: "appleme.club"
2016/07/21 05:28:07 [warn] 21835#21835: *1100 using uninitialized "rocket_reason" variable, client: 195.2.219.97, server: appleme.club, request: "GET /feed/ HTTP/1.1″, host: "appleme.club"

Have you experienced similar issue with your configuration in the past? Do you have any suggestion? My pages are properly cached and everything seems to be ok, but these errors keep showing up in my error log.

**********************************************/

Additionally, you should add your host's answer, just to be sure it is not caused by some other settings inside NGINX configuration.

Nginx on another server

Hi,

I've been testing some internal VM's and the process goes

WEB -> CLOUDFLARE -> ROUTER -> VM_NGINX -> VM_WORDPRESS

NGINX = Bitnami nginx docker
WORDPRESS = wordpress apache docker image,

Adding the script to my nginx proxy and changing $document_root into $http_host to avoid it from looking locally -> it creates links as:

"domain.nl/wp-content/cache/wp-rocket/domain.nl//wp-content/plugins/essential-grid/public/assets/css/settings.css?ver=d5190acd9a2750809b07eed7bbeac99f/index-https.html_gzip"````

Which seems okay, but no files are ever written in that directory. I checked the permissions etc, but I'm afraid it won't write cuz the proxy is on a remote server = is that right?

Gzip should be applied globally and not only on minified file

Hey,
It should be more effective to apply Gzip and expire on all CSS/JS files in one section directly.
Indeed if you don't enable minification or exclude some files, your CSS/JS won't be into the /min/ folder and gzip won't be applied.

Solution :
location ~* .(js|css)$ {

gzip_vary on;
expires max;

}

Nginx Admin + Apache + CentOS + WHM

I'm using Nginx Admin to utilize Nginx with PHP-FCGI on a CentOS server running WebHostManager + cPanel. Can I still integrate your mods to enhance WP-Rocket without using the FPM handler?

How to

How to send headers Last-Modified and Not Modified in you rocket config?

not sure this works

Hello,
thanks for your conf this did help me in setting up mine ... though i have a couple of questions :

. your locations are matching /wp-content/cache/wp-rocket/.* but if i understand correctly these location should never be hit by nginx as a html would contain userfriendly urls (/tag/somegoodpost, or / or anything else but never /wp-content/)
Maybe my understanding of nginx is poor and that is a stupid question .. but anyhow i hope you can help.

On my side i have something like this :

location ~ ^/wp-content/cache/min/ {
try_files $uri @fallback;
}
(to hit minified css and js)
AND
location / {
try_files /wp-content/cache/wp-rocket/$http_host/$cache_uri/index.html @fallback;
}

with @fallback being the php-fpm call when the file has not been cached yet

It's very different that what i could see in your script and can't figure out why.

Conflict with "Currency Switcher for WooCommerce"

One of WP Rocket's big selling point is that it is compatible with "Currency Switcher for WooCommerce" (https://aelia.co/shop/currency-switcher-woocommerce)

Both WP Rocket and Aelia state its compatibility.

However, when this nginx conf is enabled, the Currency Switcher plugin stops working correctly. Incorrect currencies (cached from sessions in other countries) show up as a result of Rocket-Nginx being enabled.

Would be great to have this fixed!

trailing index.html

Hi,

none of my files get cached and if i debug it i get the following header:

curl -I http://www.domain.de/wp-content/uploads/2015/11/picture.jpg

Output:

HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Mon, 11 Jan 2016 21:40:26 GMT
Content-Type: image/jpeg
Content-Length: 106266
Last-Modified: Sat, 14 Nov 2015 14:42:16 GMT
Connection: keep-alive
ETag: "56474848-19f1a"
Expires: Thu, 31 Dec 2037 23:55:55 GMT
Cache-Control: max-age=315360000
X-Rocket-Nginx-Bypass: No
X-Rocket-Nginx-Reason: File not cached
X-Rocket-Nginx-File: /var/www/domain.de/wp-content/cache/wp-rocket/www.domain.de//wp-content/uploads/2015/11/picture.jpg/index.html

The File has always an index.html at the end. Is this a bug?

X-Rocket-Nginx-Bypass + Connected user

Hi Maxime,

Today it's not possible to Bypass Wordpress when the user is logged because of the cookie.
If you find the cookie "wordpress_logged_in_" you set $rocket_bypass to 0.

With wp-rocket the cached files for a logged user ar inside a directory like : /wp-content/cache/wp-rocket/www.domain-Username-NUM-ID/

What if when a user is logged we add a function to create a cookie named Username-NUM-ID
and with rocket-nginx we check if this cookie exist to get his name and allow the nginx redirect ?

Do you think it will be possible ?

Thank you

Change Request for Mobile Devices

First of all, I am sorry if I should send this to you some other way. I looked and was unable to find a "feature request" or something similar. I will try to keep this short.

I host high volume WordPress sites. At least I consider them high volume. Most of my customers generate between 400 and 2000 new connections a minute. I have taught myself a lot about improving Nginx, PHP-fpm, and MariaDB performance over the last few months. Some of my customers use https; Varnish isn't really an option.

I settled on the wp-rocket caching plugin because it is paid plugin supported by an active team of developers. The price is reasonable for a Dev license that allows me to use it on several sites. Although using this plugin, in the beginning, was rocky, to say the least, the team at wp-rocket has made vast improvements over the last few months. I am very happy with the plugin.

I ran across this project on git and got excited. Only to later figure out that all of my customers use the same URL for mobile and desktop clients. This forces me to rely on the PHP code inside the wp-rocket plugin to determine if the clients are mobile or desktop. Not very efficient and I think unnecessarily complex which ends up using a lot of CPU.

Which means, for all intents and purposes, your project, while impressive, doesn't provide me any benefit.

Everyone is moving toward mobile. Over 70% of my customers' traffic is generated by mobile devices.

Here is the UGLY truth I must share. I use Plesk, and honestly I love it. The support is good enough; it is easy to customize, and it does a lot of work I don't have to do or write scripts to do for me. Did I mention the price is right? At any rate, Nginx is very powerful and there would be no need for any other front end caching if I could get your project to detect mobile vs. desktop user agents.

Here is my question/request.

  1. Do you think it would be possible to modify your project to include the needed logic to determine if the user agent is a mobile device or a desktop. After looking at the user agent then Nginx could grab the cached file from the appropriate location respectively.
  2. Would you mind if I modified your code and tested it to see who well it works? (I have some moderate non-critical domains I can play with)

This would provide a HUGE performance boost for my servers allowing me to scale them well beyond their current capabilities. I use multiple nodes, but processor time is a premium cost to me. Hardware costs big cash up front, and I am not fond of "cloud". Why pay a premium for someone else to replace bad drives now and then? (I digress)

I noticed some blogs and other forums that advise people to use a mobile redirect. This seems to add another layer of complexity. Below the body of my message are the examples I found. Would it be possible to start the entire rocket-Nginx configuration modification with a similar 'if' statement, where instead of a rewrite we declare and set the appropriate cache lookup directory which your project eventually tries before it sends the request over PHP?

Also, this was just an example I found as I trolled for answers, we could use the same "http_user_agent" as the wp-rocket plugin uses. In other words we could identify only mobile and default to desktop much like wp-rocket does (I think).

if ($http_user_agent ~* "(android|bb\d+|meego).+mobile|avantgo|bada/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)/|plucker|pocket|psp|series(4|6)0|symbian|treo|up.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino") {
set $mobile_rewrite perform;
}

if ($http_user_agent ~* "^(1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|)|g1 u|g560|gene|gf-5|g-mo|go(.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| ||a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-)") {
set $mobile_rewrite perform;
}

Can be used with fastcgi?

Sorry I couldn't find a way to contact you so I opened a new ticket.
Can this be or should be used with fastcgi cache for example or some other nginx cache system ?

Thanks!

Contributor needed - PHP Configuration generator

Many people (#38, #24) asked why their headers were not working correctly with Rocket-Nginx.

The reason is: because of the way Nginx is built. (More info here)

Rocket-Nginx version 1.2 comes with comments in the script to make things easier to generate your configuration. The configuration generator is what needs to be built.

Here is what is needed:

  1. A HTML file made of 6 textareas
  • HTTP/HTTPS headers
  • GZIP headers
  • NON-Gzip headers
  • CSS headers
  • JS headers
  • Media headers
  1. Rocket-Nginx users would then add their headers in the specific textareas.

  2. When the user hits submit, the script would then get the original script found here in PHP and the values in each textbox would be inserted in the configuration at the right place:

  • HTTP/HTTPS headers would be inserted next to : #!# HEADER_HTTP #!#
  • GZIP headers would be inserted next to : #!# HEADER_GZIP #!#
  • NON-Gzip headers would be inserted next to : #!# HEADER_NON_GZIP #!#
  • CSS headers would be inserted next to : #!# HEADER_CSS #!#
  • JS headers would be inserted next to : #!# HEADER_JS #!#
  • Media headers would be inserted next to : #!# HEADER_MEDIAS #!#
  1. It would be nice if the values were kept in the cookies for future use.

Let me know if you want to help! :-)

HSTS headers not working with rocket-nginx.conf

Hi,

after including the nginx-rocket.conf into my server{} block, my HSTS headers somehow went missing on the response.

Tried alot of things including placing the add_header at top, bottom of the server{} block or even in rocket-nginx.conf the again at top, bottom or in the if ($https = "on") {} block. Nothing did work.

Why?

    server {
            listen 10.0.0.2:443 ssl http2;
            server_name mycorp.com www.mycorp.com;
            access_log /var/log/nginx/access.log combined;
            error_log /var/log/nginx/error.log error;
            root /var/www/mycorp.com/;
            index index.php index.html index.htm;

            location / {
                    index index.php index.html index.htm;
                    try_files $uri $uri/ @rewrites;
            }

            location @rewrites {
                    rewrite ^ /index.php last;
            }


            ##########
            # SSL
            ##########
            ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
            ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA;
            ssl_prefer_server_ciphers on;
            ssl_ecdh_curve secp384r1;
            ssl_dhparam /etc/nginx/ssl/dhparam.pem;
            ssl_session_cache shared:SSL:20m;
            ssl_session_timeout 10m;
            ssl_certificate /etc/nginx/ssl/mycorp.com.crt;
            ssl_certificate_key /etc/nginx/ssl/mycorp.com.key;


            ##########
            # OCSP
            ##########
            ssl_stapling on;
            ssl_stapling_verify on;
            resolver 8.8.4.4 8.8.8.8;
            ssl_trusted_certificate /etc/nginx/ssl/mycorp.com.crt;


            ##########
            # HSTS
            ##########
            add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";


            ##########
            # PHP
            ##########
            location ~ ^(.+?\.php)(/.*)?$ {
                    try_files $1 = 404;
                    include /etc/nginx/fastcgi_params;
                    fastcgi_split_path_info ^(.+\.php)(/.+)\$;
                    fastcgi_param SCRIPT_FILENAME $document_root$1;
                    fastcgi_param PATH_INFO $2;
                    fastcgi_param HTTPS on;
                    fastcgi_pass unix:/var/run/php-fpm.socket;
                    fastcgi_index index.php;
                    add_header "X-WPFC-Cache" "MISS";
            }


            ##########
            # GZIP
            ##########
            gzip on;
            gzip_types text/css text/x-component application/x-javascript application/javascript text/javascript text/x-js text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon;


            #################
            # YOAST SITEMAP
            #################
            rewrite ^/sitemap.xml$ /index.php?sitemap=1 last;
            rewrite ^/([^/]+?)-sitemap([0-9]+)?.xml$ /index.php?sitemap=$1&sitemap_n=$2 last;
            rewrite ^/main-sitemap\.xsl$ /index.php?xsl=main last;


            ##########
            # CORS
            ##########
            location ~ \.(ttf|ttc|otf|eot|woff|font.css)$ {
                    add_header Access-Control-Allow-Origin "*";
            }

            # Include wp-rocket nginx config
            include global/rocket-nginx.conf;

            # Include global restrictions config
            include global/restrictions.conf;
    }

Thanks
Dominic

nginx+apache+wp-rocket

Hello, Maxime!
Thank you for your config, I was surprised when I found completely prepared file :)
My hosting server works with nginx+apache so I wasn't sure if I configure all in a right way...

I'd like to hear your recommendation for current setup or just check my nginx config:

server {
        listen 80;
        server_name my.site www.my.site;
        location / {
        proxy_pass         http://127.0.0.1:8080/;
        proxy_redirect     off;
        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $remote_addr;
        proxy_set_header Range "";
        client_max_body_size       10m;
        client_body_buffer_size    128k;
        proxy_connect_timeout      90;
        proxy_send_timeout         90;
        proxy_read_timeout         90;
        proxy_buffer_size          4k;
        proxy_buffers              4 32k;
        proxy_busy_buffers_size    64k;
        proxy_temp_file_write_size 10m;
        }

        # Deny files starting with a . (dot)
        location ~ /\. {
        deny all;
        }
        location ~* \.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|wav|bmp|rtf|js)$ {
        root /home/d_i180;

         # Add Rocket-Nginx configuration (of course !!)
            include rocket-nginx.conf;
        }
}

When GZIP (.html_gzip) is enabled all html request is interpreted as downloads

Hi there and thanks for this awesome conf!

I think I have the same problem as this closed issue (#45). Im using a custom path to the /cache folder. More exactly /app/cache/wp-rocket/www.example.com. When I enable the conf to read the .html_gzip file from the /cache folder it interpretes it as an download. And when I remove the _gzip it works fine.

Im using Roots.io's Trellis and Bedrock setup. I thinking it has something to do with the nginx server setup not being able to pick up .html_gzip as an valid format.

I just wanted to know if you have any input on this, before I throw it over to the guys at roots.io.

The nginx conf is found here: nginx.conf
The WordPress conf is found here: wordpress-site.conf

Not working on Plesk nginx

Hi,

I am trying to get it working on plesk based nginx. I copied all contents from rocket-nginx.conf file and pasted in nginx directives section in plesk panel at domain level. After applying the configuration my site stopped working and trying to download a random file each time with blank page. How we can get it working with plesk based nginx?

If you want then I can provide you temporary access on a temporary environment.

Regards

Beware: GZIP + Brotli

Some client (Google Search Console + Google Crawler probably) have problems decoding with Brotli compressed gzip-files. If Brotli is active on the server.

At the moment the rocket-nginx.conf just checks if the client accept gzip and than serves the _gzip-file which will compressed again with Brotli:
# Is GZIP accepted by client ?
if ($http_accept_encoding ~ gzip) {
set $rocket_encryption "_gzip";
}

For this reason I check if the client accept Brotli and unset $rocket_encryption:
# Is Brotli accepted by client ?
if ($http_accept_encoding ~ br) {
set $rocket_encryption "";
}

More headers with this conf?

When I use this conf, other headers (as X-XSS, X-Frame, X-Content, Fastcgi-cache...) disappear.

How to include all headers with this conf?

Thanks.

Replace if to map - https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/

Nginx generate separate in-memory config for each if statement, so it's hell to debug it.
https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/

Map is more convenient way for conditions. For example, you can replace
if ($http_accept_encoding ~ gzip) { set $rocket_encryption "_gzip"; }
to
map $http_accept_encoding $rocket_encryption { default ""; ~gzip "_gzip"; }

http://nginx.org/en/docs/http/ngx_http_map_module.html

No Gzip and X-Rocket-Nginx-Bypass to No for all ressources

Hi @maximejobin ,

Thanks you first of all for your work !
I saw you were currently working when you can on the version 2 but I encounter an issue with the current version and I wonder if you could help me to figure out why I can't have the ressources of any WordPress with WP Rocket gziped.
For example on this WordPress website we made : http://melvi2017.com/
"X-Rocket-Nginx-Bypass" header is set to No for every ressources and the response header doesn't have the "Content-Encoding:gzip" indication.

  • gzip is well enabled on the server
  • the configuration file is in place as we have the header "X-Rocket-Nginx-Bypass" visible
  • the hosting is managed with plesk

Do you have any ideas or solution for this ?

Many thanks,

--
Fabien

wp-content directory should be a variabe

The wp-content directory is often renamed for security reasons and it would be helpful if it a variable was created simplifying the customization in instances where the wp-content directory has been renamed.

HTTPS with Cloudflare flexible SSL

Hello,

It seems that the WP-Rocket plugin does generate a "https" cached file when accesing a website using Cloudflare Flexible SSL, even if the server is only using "http"...

So my question is, is it possible to optimize this on your side or should I report this on http://wp-rocket.me/support/ ?

Problem with subsite

Hi Maxime, first of wall thanks for this great module.
Just wanna know if it's possible this module work with subsite, for example:
My main site root is /var/www/example.com/htdocs/ and all works perfeclty.
But for the blog: /var/www/example.com/htdocs**/blog/**, the $rocket_file is looking for /var/www/example.com/htdocs/wp-content/cache/wp-rocket/www.example.com//blog//index-https.html_gzip ;(

Is there any way to make it work?

Cron job - Parse error: syntax error, unexpected '*', expecting end of file

Hey, none of the alternatives works for me, get the same error every time

Parse error: syntax error, unexpected '*', expecting end of file

Then, manually a cron job every 15 minutes (it should be enough for most websites):

*/15 * * * * wget -q -O - http://www.website.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1

or

*/15 * * * * curl http://www.website.com/wp-cron.php?doing_wp_cron > /dev/null 2>&1

or

*/15 * * * * cd /home/user/public_html; php wp-cron.php > /dev/null 2>&1

Make sure you test that your tasks still run after this change!`

YITH Wishlist count incorrect when rocket-nginx is enabled

Hi Maxime, first of all thanks for sharing your great work. I'm using it on my site at the moment. However I have some issues with YITH Wishlist plugin. For example when I have items on my wishlist, it displays the count similar to WooCommerce cart. Whenever I navigate between pages, the count changes or disappears. There are instances also when the wishlist page itself does not display the correct items until you delete an item, then it refreshes with the correct list.

I tried changing WP rocket settings and even server SSL settings until finally I was able to isolate the issue to be caused by rocket-nginx. When I exclude it from server settings, then it wishlist works. Any chance you could have a look at this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.