Increase file upload size limit in PHP-Nginx

Increase file upload size limit in PHP-Nginx

If Nginx aborts your connection when uploading large files, you will see something like below in Nginx’s error logs:
[error] 25556#0: *52 client intended to send too large body:
This means, you need to increase PHP file-upload size limit. Following steps given below will help you troubleshoot this!

Changes in php.ini

To change max file upload size to 100MB
Edit…
vim /etc/php5/fpm/php.ini
Set…
upload_max_filesize = 100M
post_max_size = 100M

Notes:

  1. Technically,  post_max_size should always be larger than upload_max_filesize but for large numbers like 100M you can safely make them equal.
  2. There is another variable max_input_time which can limit upload size but I have never seen it creating any issue. If your application supports uploads of file-size in GBs, you may need to adjust it accordingly. I am using PHP-FPM behind Nginx from very long time and I think in such kind of setup, its Nginx to which a client uploads file and then Nginx copies it to PHP. As Nginx to PHP copying will be local operation max_input_time may never create issue. I also believe Nginx may not copy the file but merely hand-over the location of file or descriptor records to PHP!
You may like to read these posts which explains PHP file upload related config in some details.

Change in Nginx config

Add following line to http{..} block in nginx config:
http {
 #...
        client_max_body_size 100m;
 #...
}
Note: For very large files, you may need to change value of client_body_timeout parameter. Default is 60s.

Reload PHP-FPM & Nginx

service php5-fpm reload
service nginx reload

Changes in WordPress-Multisite

If you are running WordPress Multisite setup, then you may need to make one more change at the WordPress end.
Go to: Network Admin Dashboard >> Settings. Look for Upload Settings
Also change value for Max upload file size

https://rtcamp.com/tutorials/php/increase-file-upload-size-limit/

Moodle 2.7 on Ubuntu server 14.04

In this tutorial I set up new Ubuntu server 14.04 and Moodle 2.7 for my school. Here is the stack:

  1. Nginx
  2. Php5-fpm
  3. MariaDB (Mysql)

Near Future upgrade: MariaDB cluster + HAProxy for High availability Database

First let update your server

sudo apt-get update && apt-get -y dist-upgrade 

Moodle installation

sudo apt-get install mariadb-server nginx php5-fpm php5-mysql graphviz aspell php5-pspell php5-curl php5-gd php5-intl php5-mysql php5-xmlrpc php5-ldap git-core

Note: remember your mysql administrator password
Checkout latest Moodle 2.7 from Git repository

cd /opt
sudo git clone git://git.moodle.org/moodle.git
cd moodle
sudo git branch -a
sudo git branch –track MOODLE_27_STABLE origin/MOODLE_27_STABLE
sudo git checkout MOODLE_27_STABLE
sudo mkdir -p /var/www/moodledata
sudo cp -R /opt/moodle /var/www/
chown -R www-data:www-data /var/www/moodle/
chown -R www-data:www-data /var/www/moodledata/
sudo chmod -R 777 /var/www/moodledata
sudo chmod -R 0755 /var/www/html/moodle

In the future just checkout update from git and copy to moodle dir

MariaDB

I left default setting for Mysql because MariaDb run InnoDB as default
Create moodle database and its user. Use your mysql root pass as installation of MariaDB

mysql -u root -p
CREATE DATABASE moodle DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,CREATE TEMPORARY TABLES,DROP,INDEX,ALTER ON moodle.* TO moodle_user@localhost IDENTIFIED BY ‘moodle_user_password’;
quit;

Php5-fpm

I run php-fpm on TCP. Edit /etc/php5/fpm/pool.d/www.conf

[www]
user = www-data
group = www-data
listen = 127.0.0.1:9000

pm = ondemand
pm.max_children = 30
pm.start_servers = 10
pm.min_spare_servers = 4
pm.max_spare_servers = 10

pm.max_requests = 50000
request_terminate_timeout = 180
php_flag[display_errors] = off
php_admin_value[error_reporting] = 0
php_admin_value[error_log] = /var/log/php5-fpm.log
php_admin_flag[log_errors] = on
php_admin_value[memory_limit] = 128M
chdir = /

service php5-fpm restart

Nginx

This box dedicated for Moodle only. Edit /etc/nginx/site-enabled/default

server {
        listen 80 default_server;
        root /var/www/moodle;
        index index.php index.html index.htm;
        server_name moolde27.mydomain.vn;
        location / {
                try_files $uri $uri/ =404;
        }
        location ~ .php$ {
                fastcgi_split_path_info ^(.+.php)(/.+)$;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                include fastcgi_params;
                }
        }

service nginx restart

 Complete Setup

Notice these Path: /var/www/moodle, /var/www/moodledata

Open your browser and go to http://moodle27.mydomain.vn

Follow the prompts selecting:

Database Type

Choose: MariaDB

Database Settings

Host server: 127.0.0.1
Database: moodle
User: moodle_user
Password: moodle_user_password
Tables Prefix: mdl_

Environment Checks

This will indicate if any elements required to run moodle haven’t been installed.

Next next next…

follow prompts and confirm installation

Create a Site Administrator Account

Create your moodle user account which will have site administrator permissions.

Installation Complete

Congrats! You can now start using Moodle!

It was extremely annoying instead of showing nice Moodle Bootstrap interface it show only text and text. Troubleshooting Nginx does not show Images and CSS
Use browser search for the text path Sites Administration > Server > HTTP
Disable Use slash arguments which is enabled by Default

Reload your Browser and BINGO!

Reference:
http://docs.moodle.org/27/en/Step-by-step_Installation_Guide_for_Ubuntu

Vì sao người lương thiện cả đời gặp nỗi buồn và trắc trở?

Vì sao người lương thiện cả đời gặp nỗi buồn và trắc trở?

Tôi đã tìm một người thầy thông thái và đạo hạnh xin chỉ bảo:

-Vì sao những người lương thiện như con lại thường xuyên cảm thấy khổ, mà những người ác lại vẫn sống tốt như vậy
Thầy hiền hòa nhìn tôi trả lời:

– Nếu một người trong lòng cảm thấy khổ, điều đó nói lên rằng trong tâm người này có tồn tại một điều ác tương ứng. Nếu một người trong nội tâm không có điều ác nào, như vậy, người này sẽ không có cảm giác thống khổ. Vì thế, căn cứ theo đạo lý này, con thường cảm thấy khổ, nghĩa là nội tâm của con có tồn tại điều ác, con không phải là một người lương thiện thật sự. Mà những người con cho rằng là người ác, lại chưa hẳn là người thật sự ác.

Một người có thể vui vẻ mà sống, ít nhất nói rõ người này không phải là người ác thật sự.

Có cảm giác như bị xúc phạm, tôi không phục, liền nói:

-Con sao có thể là người ác được? Gần đây, tâm con rất lương thiện mà!

Thầy trả lời:

-Nội tâm không ác thì không cảm thấy khổ, con đã cảm thấy khổ, nghĩa là trong tâm con đang tồn tại điều ác. Con hãy nói về nỗi khổ của con, ta sẽ nói cho con biết, điều ác nào đang tồn tại trong con.

Tôi nói:

-Nỗi khổ của con thì rất nhiều! Có khi cảm thấy tiền lương thu nhập rất thấp, nhà ở cũng không đủ rộng, thường xuyên có “cảm giác thua thiệt” bởi vậy trong tâm con thường cảm thấy không thoải mái, cũng hy vọng mau chóng có thể cải biến tình trạng này; trong xã hội, không ít người căn bản không có văn hóa gì, lại có thể lưng quấn bạc triệu, con không phục; một trí thức văn hóa như con, mỗi tháng lại chỉ có một chút thu nhập, thật sự là không công bằng; người thân nhiều lúc không nghe lời khuyên của con, con cảm thấy không thoải mái…

Cứ như vậy, lần lượt tôi kể hết với thầy những nỗi thống khổ của mình.

Thầy gật đầu, mỉm cười, một nụ cười rất nhân từ đôn hậu, người từ tốn nói với tôi:

Thu nhập hiện tại của con đã đủ nuôi sống chính con và gia đình. Con còn có cả phòng ốc để ở, căn bản là đã không phải lưu lạc nơi đầu đường xó chợ, chỉ là diện tích hơi nhỏ một chút, con hoàn toàn có thể không phải chịu những khổ tâm ấy.
-Nhưng, bởi vì nội tâm con có lòng tham đối với tiền tài và của cải, cho nên mới cảm thấy khổ. Loại lòng tham này là ác tâm, nếu con có thể vứt bỏ ác tâm ấy, con sẽ không vì những điều đó mà cảm thấy khổ nữa.

Trong xã hội có nhiều người thiếu văn hóa nhưng lại phát tài, rồi con lại cảm thấy không phục, đây chính là tâm đố kị. Tâm đố kị cũng là một loại ác tâm. Con tự cho mình là có văn hóa, nên cần phải có thu nhập cao, đây chính là tâm ngạo mạn. Tâm ngạo mạn cũng là ác tâm. Cho rằng có văn hóa thì phải có thu nhập cao, đây chính là tâm ngu si; bởi vì văn hóa không phải là căn nguyên của sự giàu có, kiếp trước làm việc thiện mới là nguyên nhân cho sự giàu có của kiếp này. Tâm ngu si cũng là ác tâm!

Người thân không nghe lời khuyên của con, con cảm thấy không thoải mái, đây là không rộng lượng. Dẫu là người thân của con, nhưng họ vẫn có tư tưởng và quan điểm của riêng mình, tại sao lại cưỡng cầu tư tưởng và quan điểm của họ bắt phải giống như con? Không rộng lượng sẽ dẫn đến hẹp hòi. Tâm hẹp hòi cũng là ác tâm.

Sư phụ tiếp tục mỉm cười:

– Lòng tham, tâm đố kỵ, ngạo mạn, ngu si, hẹp hòi, đều là những ác tâm. Bởi vì nội tâm của con chứa đựng những ác tâm ấy, nên những thống khổ mới tồn tại trong con. Nếu con có thể loại trừ những ác tâm đó, những thống khổ kia sẽ tan thành mây khói.”

Con đem niềm vui và thỏa mãn của mình đặt lên tiền thu nhập và của cải, con hãy nghĩ lại xem, căn bản con sẽ không chết đói và chết cóng; những người giàu có kia, thật ra cũng chỉ là không chết đói và chết cóng. Con đã nhận ra chưa, con có hạnh phúc hay không, không dựa trên sự giàu có bên ngoài, mà dựa trên thái độ sống của con mới là quyết định. Nắm chắc từng giây phút của cuộc đời, sống với thái độ lạc quan, hòa ái, cần cù để thay thế lòng tham, tính đố kỵ và ích kỷ; nội tâm của con sẽ dần chuyển hóa, dần thay đổi để thanh thản và bình an hơn.

-Trong xã hội, nhiều người không có văn hóa nhưng lại giàu có, con hãy nên vì họ mà vui vẻ, nên cầu chúc họ càng giàu có hơn, càng có nhiều niềm vui hơn mới đúng. Người khác đạt được, phải vui như người đó chính là con; người khác mất đi, đừng cười trên nỗi đau của họ. Người như vậy mới được coi là người lương thiện! Còn con, giờ thấy người khác giàu con lại thiếu vui, đây chính là tâm đố kị. Tâm đố kị chính là một loại tâm rất không tốt, phải kiên quyết tiêu trừ!”

Con cho rằng, con có chỗ hơn người, tự cho là giỏi. Đây chính là tâm ngạo mạn. Có câu nói rằng: “Ngạo mạn cao sơn, bất sinh đức thủy” (nghĩa là: ngọn núi cao mà ngạo mạn, sẽ không tạo nên loại nước tốt) người khi đã sinh lòng ngạo mạn, thì đối với thiếu sót của bản thân sẽ như có mắt mà không tròng, vì vậy, không thể nhìn thấy bản thân có bao nhiêu ác tâm, sao có thể thay đổi để tốt hơn. Cho nên, người ngạo mạn sẽ tự mình đóng cửa chặn đứng sự tiến bộ của mình. Ngoài ra, người ngạo mạn sẽ thường cảm thấy mất mát, dần dần sẽ chuyển thành tự ti. Một người chỉ có thể nuôi dưỡng lòng khiêm tốn, luôn bảo trì tâm thái hòa ái từ bi, nội tâm mới có thể cảm thấy tròn đầy và an vui.

-Kiếp trước làm việc thiện mới chính là nguyên nhân cho sự giàu có ở kiếp này, (trồng dưa được dưa, trồng đậu được đậu). Mà người thường không hiểu được nhân quả, trồng dưa lại muốn được đậu, trồng đậu lại muốn được dưa, đây là thể hiện của sự ngu muội. Chỉ có người chăm học Phật Pháp, mới có được trí huệ chân chính, mới thật sự hiểu được nhân quả, quy luật tuần hoàn của vạn vật trong vũ trụ, nội tâm mới có thể minh tỏ thấu triệt. Để từ đó, biết làm thế nào lựa chọn tư tưởng, hành vi và lời nói của mình cho phù hợp. Người như vậy, mới có thể theo ánh sáng hướng đến ánh sáng, từ yên vui hướng đến yên vui.”

-Bầu trời có thể bao dung hết thảy, nên rộng lớn vô biên, ung dung tự tại; mặt đất có thể chịu đựng hết thảy, nên tràn đầy sự sống, vạn vật đâm chồi! Một người sống trong thế giới này, không nên tùy tiện xem thường hành vi và lời nói của người khác. Dẫu là người thân, cũng không nên mang tâm cưỡng cầu, cần phải tùy duyên tự tại! Vĩnh viễn dùng tâm lương thiện giúp đỡ người khác, nhưng không nên cưỡng cầu điều gì.

-Nếu tâm một người có thể rộng lớn như bầu trời mà bao dung vạn vật, người đó sao có thể khổ đây?

Vị thầy khả kính nói xong những điều này, tiếp tục nhìn tôi với ánh mắt đầy nhân từ và bao dung độ lượng.

Ngồi im lặng hồi lâu…xưa nay tôi vẫn cho mình là một người rất lương thiện, mãi đến lúc này, phải! chỉ đến lúc này, tôi mới biết được trong tôi còn có một con người rất xấu xa, rất độc ác! Bởi vì nội tâm của tôi chứa những điều ác, nên tôi mới cảm thấy nhiều đau khổ đến thế. Nếu nội tâm của tôi không ác, sao tôi có thể khổ chứ ?

Xin cảm tạ thầy, nếu không được người khai thị dạy bảo, con vĩnh viễn sẽ không biết có một người xấu xa như vậy đang tồn tại trong con!

Zabbix monitor VMWare Infrastructure

Zabbix monitor VMWare Infrastructure

Monitor VMware is new feature of Zabbix 2.2
I got alot of disadvantages at this moment, can’t get the most from guest machine: host IP address, host status, trigger, action… But it worth a try.

To turn on VMware monitoring, Zabbix extensions –with-libxml2 –with-libcurl needs to be compiled with. In addition, the configuration file zabbix_server.conf StartVMwareCollectors must be set to 1 or higher.

apt-get install libxml2-dev libcurl


Edit /etc/zabbix/zabbix_server.conf

LogFile=/tmp/zabbix_server.log
DBName=zabbix
DBUser=zabbix
DBPassword=
StartTrappers=5
StartVMwareCollectors=5
VMwareFrequency=10
VMwareCacheSize=32M
ListenIP=0.0.0.0
StartPollers=96
CacheSize=64M
HistoryCacheSize=16M
TrendCacheSize=16M
HistoryTextCacheSize=32M
ValueCacheSize=16M

Use the following procedure to monitor VMware.

  1. Create a host of vCenter VMware hypervisor or (vSphere / ESXi)
  2. $ {URL} , {$ USERNAME} , {$ PASSWORD}
    $URL -> https://(name/IP of vSphere Host or vCenter)/sdk
    You must have access to the URL. Try test it first. If it not work go to your VCenter and adjust it.
  3. Apply “Template Virt VMware” to host
  4. Hypervisor, guest VM is automatically registered by the discovery, monitoring is started. It take more than 2 hours to fetch the Information from VCenter. That’s it

Pixeluvo – Photoshop Alternative for Linux

I started using Linux since 2008. I always saught for a Photoshop alternative for my Photography stuff and always get disapointed. From Photoshop + Wine, Photoshop + Vitualbox, Pinta, Gimp, Picasa, Shotwell, Darktable.
But this time I discover a super lightweight and easy to use software call Pixeluvo. It not a free software but provide 30 days trial after that you can purchase around 40$. It made me a feeling of a modern Photoshop interface its legendary hot key and layer system.

Zabbix change Global SNMP Community String

Using the default community string of public is not exactly safe and you can chose to change it in your devices.

When you do you’ll need to update the {$SNMP_COMMUNITY} macro to reflect this:

In Zabbix Dashboard go to Administration > General > Macro’s set the {$SNMP_COMMUNITY} macro to the SNMP Community name.

A Beginner’s Guide to HTTP Cache Headers

A Beginner’s Guide to HTTP Cache Headers

This article offers an exploration into HTTP caching headers and associated CDN behaviour. If you’re looking to understand how caching headers fit into the modern web, or are just curious about what everyone is talking about around you, this resource is for you.

If you already understand the benefits of cache headers and are looking to extend your knowledge further, I’d recommend referring to the W3 documentation.

What Can Cache Headers Do for You?

Simply put, caching allows you to store your web assets on remote points along the way to your visitors’ browsers. Of course the browser itself also maintains an aggressive cache, which keeps clients from having to continually ask your server for a resource each time it comes up.
Cache configuration for your web traffic is critical for any performant site. If you pay for bandwidth, make revenue from an e-commerce site, or even just like keeping your reputation as a web-literate developer intact, you need to know what caching gets you and how to set it up.
In the case of assets, things like your company logo, the favicon for your site, or your core CSS files aren’t likely to change from request to request, so it is safe to tell the requester to hold onto their copy of the asset for a while. If your visitors were small children in the backseat asking, “Are we there yet?” repeatedly, this would be like telling them, “No, and we won’t be for 20 more minutes, so remember my answer.”
By cutting down on the requests your server has to deal with, you are able to handle more requests, and your users will enjoy a faster browsing experience. Generally, assets like images, JavaScript files, and style-sheets can all be cached fairly heavily, while assets that are dynamically generated, like dashboards, forums, or many types of web-applications, benefit less, if at all. If your concern is performance, your dynamic content will be shunted to a bare minimum of AJAX-type resources, while the rest of your assets will be heavily cached.

For Clients & CDNs

Historically, cache settings were all about the client’s browser, so we shouldn’t forget the benefits of properly considering the client and the way it keeps assets around during a session and on return visits. However, these days, with the advent of Content Delivery Networks (CDNs), a bigger concern is how caching is handled on the intermediary points of web traffic.
What are CDNs?
In case you don’t want to read the wiki article , I’ll give you the crib notes here. Essentially, CDNs are servers, (note the plural), that sit between your end user and your server. Each of these servers are designed to cache your content according to the cache rules you set in the various HTTP headers outlined below.
When configured properly, CDNs will deliver content to your end user from the fastest, (and typically closest) server available. Additionally, CDNs act as a buffer between you and your users. The number we are most concerned with is the cache hit ratio, which describes the percentage of requests the CDN was able to answer out of its own cache without having to bother our servers. Depending on your traffic and architecture, this number can get well into the high nineties, although even at lower figures you’ll experience a gain. (Keep in mind that a low frequency of requests will mean a larger percentage of requests go back to your server, so the ratio is only meaningful when understood together with your cache times and the general load of your site.) A word of warning though; if you just setup your cache and fail to configure your caching headers correctly, it’s quite possible to end up paying twice for every request.

Basic CDN Diagram.A basic flow of data through a CDN. Your webservers provide content to the CDN intermediary servers, which have Points of Presence in various geographic regions. Lazy network diagram makers will usually just draw a cloud here.

Beyond their intended use for caching, CDNs also have a pleasant side-effect; provided you’re dealing with a website, or a particularly well-crafted web application, in the event that your servers experience a momentary outage, your CDN may be able to buffer the experience for your end users, ensuring they never even notice.

The Basic Headers

So, you know what a CDN is, and you know you want to configure your response headers to make use of them. Most web servers make it trivial to set response headers, so I’ll leave it to you, Google, and the man pages to figure that part out. For now, let’s move onto what headers you should care about.

1. cache-control

If there were a default super-header for caching behaviour, this would be it. Typically you will see a string of settings for this header along the lines of:
cache-control: private, max-age=0, no-cache
These settings are called cache response directives, and are as follows:
private | public
Essentially they let intermediary caches know that a given response is specific to the end user and should not be cached. Do not make the mistake of assuming that this in any way provides you with some kind of security or privacy: Keep using SSL for that.
no-cache
When used alone, this guy lets you specify that caches should revalidate this resource every time, typically using the “etag” header outlined below. The fun bit comes when you specify a field name after the no-cache directive, which lets caches know that you can cache the response, provided that the named fields are stripped out; cookies would be a good example of why you might want to do this. I should note that older User Agents won’t respect this trick, so you shouldn’t depend on it too much.
no-store
This guy lets you specify that caches should not store this response. I know that may be surprising given the name, but there it is. Actually, if the cache in question is following the rules, it will also ensure that no part of the request is stored either. “no-store” was designed with sensitive information requirements in mind, and so is kind of like the G-Man of cache headers.
max-age
Traditionally, you would let caches know when an asset is expired by using the aptly-named “expires” header, discussed below. However, if you want to be more explicit, you may set a max-age, in seconds, which will override the expires header. Further reasons to use this directive are discussed below under the Caveats section.
s-maxage
Using our keen deductive skills, we can see some similarities between this header and the last one. “s-” is for shared, as in “shared cache”, as in CDN. These directives are explicitly for CDNs and other intermediary caches. When present, this directive overrides both the max-age and expires header, and most well behaved CDNs will obey it.
must-revalidate
This one is fun, although not applicable to most of us. For the sake of completeness, and in case your dev-team has some kind of trivia night where free beer is involved, we’ll discuss it. Essentially, if your responses include this directive, you are telling the cache that it needs to revalidate a cached asset on any subsequent request, and that it may not, under any circumstance, serve stale content (which is sometimes a desired behaviour). Of course, I say “under any circumstances”, but what I really mean is that there’s a big fat asterisk next to that claim. If your users are under “severe connectivity constraints”, (perhaps they are browsing from low-earth-orbit), then their user agents may serve stale content, provided they pinky-swear to tell their users that they’ve done so. Apparently this directive exists because some protocols require it, typically involving transactions.
no-transform
“Transform into what?”, you’re surely asking. Some proxies will convert image formats and other documents to improve performance. Presumably this was thought to be a feature that you should have to opt out of. If you don’t like the idea of your CDN making automated guesses about how your content should be encoded or formatted, I suggest including this header.
proxy-revalidate
Essentially the same as the “must-revalidate” directive, except it’s just for the shared caches. Why didn’t they call it “s-mustrevalidate”? I’m sure there exists a mailing list somewhere where you could find that debate, but for now, just know that like “s-maxage”, this directive is designed for intermediary proxies and not user agents. The idea here is that you validate each end-user only once between the proxy and their agent, but each new user should revalidate back to the server. I suspect if your service requires this feature, you probably already know about it.
As always, you should check out the spec for these settings if you need any clarification.

2. expires

Back in the day, this was the standard way to specify when an asset expired, and is just a basic date-time stamp. It is still fairly useful for older user agents, which cryptowebologists assure us still roam in the uncharted territories. On most modern systems, the “cache-control” headers “max-age” and “s-maxage” will take precedence, but it’s always good practice to set a matching value here for compatibility. Just make sure you format the date correctly, or it will be evaluated as an expired date:
Thu, 01 Dec 1983 20:00:00 GMT
Try to avoid setting the value to more than one year out as that breaks the specification, (see below for a discussion on cache time settings).

3. etag

Short for “entity-tag”, the etag is a unique identifier for the resource being requested, typically comprised of the hash of that resource, or a hash of the timestamp the resource was updated. Basically, this lets a client ask smarter questions of the CDNs, like “give me X if it’s different than the etag I already have.”
There’s a neat trick you can do with etags, which is to make them weak validators. This basically tells the user that although they are not the same, the two resources are functionally equivalent. Support for this feature is considered optional though, so you will want to do some testing with your providers, (discussed below).

4. vary

Oh wow. This one is fun. The “vary” header is extremely powerful, but can trip up what would otherwise be a simple caching scheme. IE has had issues handling the “vary” header in the past, and at one point, even Chrome was handling this in a funny way. Essentially, “vary” lets the caches know which of the headers to use to figure out if they have a valid cache for a request; if a cache were a giant key-value store, adding “vary” fields appends those values to the key, thus changing which requests are considered valid matches for what exists in the cache.
You would commonly set this to something like “Accept-Encoding” to make sure your gzip’ed assets get served where appropriate, saving you all that bandwidth you might otherwise waste. Additionally, setting:
vary: User-Agent
will put you in the SEO good-books if you happen to be serving different versions of your HTML/CSS depending on the User-Agent of the request. Google will note the header and have the Googlebot crawl your mobile content as well.

5. pragma

Another beast from the days of yore, the “pragma” header does many things, and most of them are honoured by newer implementations. The directive we’re most concerned with is:
pragma: no-cache
which gets interpreted by newer implementations as:
cache-control: no-cache
I would not generally recommend worrying about it, but for the sake of completeness, there it is. No new HTTP directives will be defined for “pragma” going forward.

Some Caveats

Now that we’ve gotten some of the standard and expected behaviours out of the way, we should probably mention that not every CDN or User Agent will behave according to the specification, which I’m sure is not news to anyone familiar with browser compatibility issues. For this reason, it is a good idea to test your services before launching a live resource to make sure the behaviour you get is what you expected; it will save you money.
Also, you may have noted that a lot of the headers seem to be either duplicated or overlapping. Some of this is because there are subtle differences between the different methods, and also because the web is shifting over from HTTP/1.0 to HTTP/1.1, which uses the “cache-control” much more heavily. Generally it is safe to set both and let the CDNs and User Agents figure out which one they care to listen to.

1. Compression

Remember that “Accept-Encoding” example for the “vary” header we talked about? That’s your new best friend if you intend to serve compressed content, which I hope you do to increase performance and save on bandwidth. CDN providers that get a request with “gzip” as an accepted encoding are expected to request the compressed asset from the origin server, or to serve a cached version of that compressed asset. Historically, this has been a sticking point for some CDNs, and for people wishing to use something like S3 to serve their files, although modern CDNs are able to perform the compression operation themselves if need be.
Things to watch out for when the CDN serves compressed assets is that they’ll often ensure that both uncompressed (AKA identity) and gzip’ed version are in their cache, regardless of which was requested. There is a time delay as they perform that operation, so any testing you do will have to take that delay into account.

2. SSL

A CDN is basically a Man-In-The-Middle, meaning you need to think about your HTTPS traffic and how it gets back to your server. Many CDNs will pipe a request forhttps://somesite.com/asset to your servers as http://somesite.com/asset, so if your server logic depended on that being SSL, either reconsider your logic or ask your CDN to redirect to an HTTPS origin URL. Most CDNs are capable of doing so, with varying degrees of flexibility.

But What about Dynamic Content?

Generally the rule of thumb for dynamic content, like the HTML files of a WordPress blog, is to set “cache-control: no-cache” and prevent the CDNs or User Agents from storing the asset. For most applications, serving your own dynamic content is probably fine, however if you need to boost performance, read on.

Typical Dynamic Content

HTTP/1.1 200 OK
Server: Apache
X-Rack-Cache: miss
ETag: "e6811cdbcedf972c5e8105a89f637d39-gzip"
Status: 200
Content-Type: text/html; charset=utf-8
Expires: Mon, 29 Apr 2013 21:44:55 GMT
Cache-Control: max-age=0, no-cache, no-store
Pragma: no-cache
Date: Mon, 29 Apr 2013 21:44:55 GMT

An example of a section of a header for dynamic content. Note the missed cache status, and the cache-control directives all set to 0 seconds.

Most dynamic content has a shelf-life and is not nearly as volatile as we assume. Things like “Active Users” are probably valid for 10 or 20 seconds, depending on your site. Dashboards that report daily figures could certainly stand to be cached for a few minutes. News feeds could certainly stand to be cached for a while, especially if you remember to set an “etag”. If your site is seeing lots of load, it may be worth trying out a short cache on your dynamic assets.

An Analysis of Cache Time

So what types of cache times should you consider setting? Again, this will require you to consider things like the rate of traffic to your site, how sizeable your assets are, and how large your cache is, (yes, there are space allocations, so don’t go over them).
Additionally, you should consider the main tradeoff: speed and performance vs. control. If you want to update an asset and need the new version to be live immediately, you may run into trouble if you thought a one-year cache time was a good idea, especially if you set that for Users (max-age) and not just CDNs (s-maxage).
The longest you can set your headers and still be following the specification is one year, or 31536000 seconds, but this is not a very good idea. That’s like getting a face tattoo; it stays around forever, barring expensive or painful removal surgery, which accurately describes the annoyances of having to trick caches into refetching an asset through name changes or hoping you remembered to correctly set your etag and that your users and CDNs implemented them correctly. If your servers can’t stand to have your CDNs ask once a day if your profile picture has changed you should upgrade your servers.

Sane Static Content Headers

HTTP/1.1 200 OK
Cache-Control: no-transform,public,max-age=300,s-maxage=900
Content-Type: text/html; charset=UTF-8
Date: Mon, 29 Apr 2013 16:38:15 GMT
ETag: "bbea5db7e1785119a7f94fdd504c546e"
Last-Modified: Sat, 27 Apr 2013 00:44:54 GMT
Server: AmazonS3
Vary: Accept-Encoding
X-Cache: HIT

A sample of cache settings for a static asset served from S3. Here we see that the cache has been asked to store the asset for 900 seconds rather than the 300 seconds set for User Agents. Also note the “x-cache: HIT” header, indicating the CDN served the request.

There is one exception to the “thou-shalt-not-set-one-year-headers” commandment, or more accurately, there’s a bit of a hack to get around their pitfalls: if you’ve configured your site to generate resource names, you can rename your assets each time you publish a new version. Typically, this will involve an incrementing version number, a date-time stamp, or a hash of the contents, much like an “etag”, being appended to the file name, so that you end up with things like “core.E89A123FFDB…432D687B.css” and the like. It’s not pretty, but really, who cares? Also, this lets you set one-year-headers without worrying about updating your resources.
A handy table best explains the cache time trade-off. Assuming a web asset get 500 requests per minute, then the following Hit Ratios are possible for each cache time:
Cache time (minutes)Hit RatioRequest to Origin / Hr
199.8%60
599.96%12
2099.99%3
6099.997%1
8640099.9998%<1
There. It’s spelt out. What kind of Hit Ratio do you need? Typically 60 seconds to an hour is an ideal trade-off. For pseudo-dynamic content, you can still use CDNs, just start working in the under-60-seconds range, as appropriate for the request.

Testing Your CDN

So, onto the testing. Always check that the headers are coming through CDNs the way you expect when setting up new services. Typically a CDN will insert some kind of “x-” header to indicate that it hit, missed, or served expired content. What we’re looking for is a convenient way to look at this and other headers, and to set them on our requests for testing. There are more than a few tools out there to help, though these are the ones I’ve found most handy.

1. Web Inspector

Probably the most accessible method, simply right-click on a webpage in Chrome, click Inspect Element, navigate to the Network tab, hit refresh, and click on the HTML asset at the top. If it’s not selected by default, checkout the Headers tab to see all your request and response headers. Chrome also lets you set the user agent you request with, and gives you the option to not use your local cache, which is handy when you’re testing.

2. Charles Proxy et al.

Tools like Charles Proxy will let you route traffic through them and manipulate DNS lookups, record headers, and see performance statistics, all in a clean, easy-to-use GUI. These tools are generally more task-specific than the Web Inspector and other browser tools, and generally worth the small licensing fee if you work with web requests in any significant way.

3. cURL

Quick, easy, and highly flexible, cURL lets you make web requests directly from the command line and check out the responding headers. Helpful flags include -A for user agents, -b for cookies, -F for form data, -H for setting headers, and -I to request the header only. Very handy for sanity checks, and extremely powerful.

4. hurl.it

hurl.it is essentially cURL with a prettier interface, and in a webbrowser. You’re able to set the headers you pass in to the request, as well as view the full header and body response. Although you don’t quite get the robustness of the command line, it’s still very useful for a quick header examination, and is probably the fastest way to get access to headers if you’re in a hurry.

5. Python and Requests

Requests is a great Python package for making web requests, and is useful for quick checks from the REPL, or from slightly more complex scripted checks. Using Requests comes with the added benefit of letting you write a test-suite for your web assets to assert the status of response headers.

Notes from the Field and Parting Thoughts

So now you’ve made it all the way through our quick guide to cache headers, and you’re eager to get going on setting your own. Excellent. However, now it’s time to put some of this in perspective.
Most web servers, like Apache and Nginx, will do a lot of this work for you. Really, the “cache-control” header is the only one you’re going to have to work with. Web browsers are typically set up to cache aggressively to improve user experience, so often you’ll be fighting to prevent caching rather than ensuring it. Generally this means that you set a “/static” path and configure its caching headers to allow caching up to some reasonable interval like 300 seconds. Next, you would ensure that your root path “/” has “cache-control: no-cache” enabled, or better yet route dynamic content straight to your servers and only have “/static” use your CDN. This is a healthy starting point for most purposes. If your hosting bill is astronomical, or you get to use operations cost savings as beer money, then consider tweaking your settings.
CDNs will often give you the option of breaking protocol and will cache for whatever period you like, regardless of the headers. They also take liberties with the protocols depending on their interpretation of expected behaviour, which is why it’s important to test the headers you get out of your CDN and compare them to your servers. Consider the expected behaviour outlined here to be a baseline and keep an eye out for variance.
Good luck, and happy caching!

 

Steve Jobs & Thiền

Về cuộc đời Jobs, có một điểm đặc biệt người ta ít để ý, đó là Thiền. Jobs bắt đầu tìm hiểu Thiền từ rất sớm. Tư tưởng của Thiền đã ảnh hưởng đến triết lý sống và tư duy trong công việc của ông.
Một khoảnh khắc Thiền của Steve Jobs – Ảnh chụp tại nhà, năm 1982.
Tư tưởng của Thiền đã ảnh hưởng đến triết lý sống và tư duy trong công việc của Steve Jobs.
Steve Jobs, Chủ tịch của Apple, là một doanh nhân thành công và được ngưỡng mộ bậc nhất thế giới. Thế nên, người ta thường chỉ biết về khía cạnh công việc của ông, tức quá trình ông đưa Apple thành một trong những công ty có giá trị thị trường cao nhất thế giới.
Đi tìm minh triết
Năm 17 tuổi, Jobs bước vào đại học với một nỗi băn khoăn. “Tôi hoàn toàn không biết tôi muốn gì ở cuộc sống này, cũng như không biết làm thế nào để việc học đại học có thể giúp tôi tìm ra câu trả lời”. Điều Jobs thấy rõ nhất là ông đang tiêu tốn khoản tiền tiết kiệm cả đời của cha mẹ, những người thuộc giai cấp lao động, cho những gì ông “không hề thấy có giá trị.” Jobs bỏ học và sống một cách cơ cực sau đó.
Jobs phải ngủ nhờ dưới sàn phòng của bạn. Để có tiền mua thức ăn, ông phải thu từng chai nước ngọt trả lại cho đại lý để nhận khoản đặt cọc 5 xu/chai. Mỗi tối Chủ nhật, Jobs phải lội bộ hơn 11 km xuyên thành phố để có được một bữa ăn ngon miễn phí tại đền Hare Krishna (Ấn Độ Giáo).
Nói về những ngày tháng cơ cực đó, Jobs chia sẻ: “Tôi yêu khoảng thời gian này. Phần lớn những gì tôi tiếp xúc từ sự tò mò và trực giác của mình về sau đều trở nên vô giá đối với tôi”. Thường xuyên đến đền Hare Krishna vào mỗi tối Chủ nhật là cơ duyên cho hành trình tìm minh triết tại Ấn Độ của Jobs sau đó.
Năm 1973, Jobs cùng một người bạn là Daniel Kottke, lang thang khắp Ấn Độ để “tìm kiếm sự giác ngộ tâm linh”. Không may cho Jobs, vị minh sư bí ẩn mà ông muốn diện kiến vừa qua đời. Không tìm được sự giác ngộ tâm linh như mong muốn, ông trở về California trong trang phục của một nhà sư.
Trở về Mỹ, Jobs dành nhiều thời gian tìm hiểu về Thiền tại Trung tâm Thiền Los Altos ở California trước khi nghiên cứu sâu hơn về Thiền dưới sự hướng dẫn của Thiền sư Kobun Chino Otogawa, người về sau được Jobs mời làm “cố vấn tâm linh” cho công ty phần mềm NeXT.
Năm 1976, sau 3 năm tầm sư học đạo, Jobs cùng người bạn cũng bỏ học đại học như mình là Steve Wozniak thành lập Apple. Nhìn lại chặng đường Jobs đã đi qua, có thể thấy những tư tưởng Thiền mà ông tiếp xúc khi còn trai trẻ đã để lại nhiều dấu ấn trong cuộc đời và sự nghiệp của ông.
Tư tưởng “Ma”, “Sơ tâm” và chìa khóa đến sự vĩ đại
Ma là một tư tưởng cốt lõi của Thiền, lý giải mối quan hệ giữa tánh không (emptiness) và hình tướng (form), hay làm thế nào mà sự trống rỗng hình thành nên vật thể. Hãy lấy chiếc nhẫn làm ví dụ, điều gì khiến cho vật này có ý nghĩa?
Câu trả lời là chính khoảng không gian trống rỗng mà vòng kim loại chứa đựng chứ không phải bản thân vòng kim loại đó. Đây cũng là bí mật trong triết lý thiết kế sản phẩm của Jobs. Nhờ đó, sản phẩm của Apple đã đạt đến sự tiện giản đến mức gần như trống rỗng.
Apple sẵn sàng loại bỏ tất cả chi tiết, nút bấm không cần thiết để sản phẩm của mình sở hữu “những khoảng trống đầy ý nghĩa”, tạo nên sức hút khó cưỡng lại đối với người sử dụng.
Sơ tâm tức cái tâm của người mới bắt đầu. Khái niệm này xuất phát từ Thiền Phật giáo được Thiền sư người Nhật Shunryu Suzuki phổ biến rộng rãi ở Mỹ trong thập niên 1960. Khái niệm nói đến sự cởi mở và mức độ sẵn sàng học hỏi của một người. “Với tâm trí của người mới bắt đầu, bao giờ cũng xuất hiện nhiều cơ hội, nhưng với tâm trí của một chuyên gia, thì hầu như không có cơ hội nào”, Thiền sư Suzuki từng giảng như thế về Sơ tâm.
Jobs là “người mới bắt đầu” đích thực. Thành lập Apple ở tuổi 20 cùng người bạn là bước đi đầu tiên của ông. Sau 10 năm, từ công ty có trụ sở tại phòng ngủ và ga-ra, Apple đã vươn mình trở thành công ty trị giá 2 tỉ USD với hơn 4.000 nhân viên. Ở tuổi 30, Jobs bị chính công ty mình sáng lập nên sa thải.
“Tôi không biết phải làm gì trong nhiều tháng sau đó. Tôi gần như muốn trốn chạy khỏi mọi thứ. Nhưng tôi dần nhận ra rằng tôi vẫn say mê những gì mình làm. Nên tôi quyết định khởi đầu lại. Khi đó tôi chưa nhận ra việc bị sa thải chính là điều tốt đẹp nhất từng xảy đến với tôi. Gánh nặng thành công được thay thế bằng sự thoải mái khi được trở lại thành một người mới bắt đầu, không chấp vào bất cứ thứ gì. Điều đó đã giải phóng tôi, cho tôi bước vào những giai đoạn sáng tạo nhất của cuộc đời”, Jobs cho biết.
Và như thế, NeXT và Pixar lần lượt ra đời. Cả 2 công ty đều mang đậm dấu ấn đột phá của Steve Jobs. NeXT tiên phong trong lĩnh vực thiết kế phần mềm máy tính và nổi tiếng nhờ một tập thể thiên tài do Jobs tập họp được. Còn Pixar dưới sự dẫn dắt của Jobs chính là công ty đầu tiên trên thế giới sản xuất bộ phim hoạt hình từ đồ họa máy tính, Toy Story.
Hiện nay, Pixar vẫn là hãng phim đồ họa thành công nhất thế giới. Trở lại “mái nhà xưa” Apple năm 1997 để tiếp quản chiếc ghế Tổng Giám đốc, Jobs tiếp tục vận dụng lối tư duy của “người mới bắt đầu” để từng bước khai sinh ra các sản phẩm Apple “trước nay chưa hề có” nhưng mang lại thành công bền vững cho Apple từ đó về sau. Đó là iMac, Max OS X, iPod, iTunes, iPhone và gần đây nhất là iPad.
Quan niệm về cái chết và quá trình ra quyết định
Jobs từng chia sẻ quan điểm của ông về cái chết cũng như tầm quan trọng của việc nhận biết đúng đắn về cái chết:
“Không ai muốn chết cả. Thậm chí những người thích lên thiên đàng cũng không muốn chết. Tuy nhiên, cái chết là đích đến chung của mỗi chúng ta và không ai có thể tránh khỏi. Nhưng Cái Chết thật ra lại là một trong những tạo vật tuyệt vời nhất của Sự Sống. Nó là tác nhân làm thay đổi cuộc sống, dẹp bỏ cái cũ, dọn đường cho cái mới.
“Luôn ghi nhớ rằng mình sẽ chết chính là công cụ quan trọng nhất giúp tôi ra những quyết định lớn trong cuộc sống. Vì hầu như mọi thứ như sự kỳ vọng, niềm tự hào của người khác, hay sự sợ hãi thất bại đều tan biến khi đối diện với cái chết”, Jobs cho biết và nói tiếp: “Luôn ghi nhớ rằng mình sẽ chết chính là cách tốt nhất giúp tôi tránh được cái bẫy tư duy khiến tôi tin rằng mình có một điều gì đó để mất. Bản thân tôi vốn đã không có gì nên không có lý do gì để không nghe theo con tim mình cả”.
Ông cũng cho rằng thời gian của bất cứ ai cũng có giới hạn nên đừng lãng phí nó mà sống cuộc đời của người khác. Đừng mắc kẹt vào những giáo điều, sống với quan điểm của người khác. Đừng để những huyên náo từ quan điểm của người khác dìm chết tiếng nói nội tâm của mình. Và quan trọng nhất là dũng cảm làm theo con tim và trực giác. Theo một cách nào đó, chúng đã biết những gì một người thật sự muốn trở thành. Những thứ khác đều không quan trọng.
Jobs còn đề cập đến một vấn đề quan trọng: hãy dám là chính mình, dám sống cuộc đời của mình, sống với tiếng nói của con tim và trực giác, để trở thành những gì mình thật sự muốn trở thành. Ông khuyên mọi người: “Hãy luôn khát khao và hãy dám dại khờ”, để có thể làm nên những điều vĩ đại.
Theo Hoàng Trung
NCĐT
Một khoảnh khắc Thiền của Steve Jobs - Ảnh chụp tại nhà, năm 1982.
Một khoảnh khắc Thiền của Steve Jobs – Ảnh chụp tại nhà, năm 1982.