Aug 06

nginx – how location directive match performed

i am new to nginx! i tried to config nginx to server php only from site root,and only some php file to be excuted from a sub – directory. i need to get more detail about location.

This directive allows different configurations depending on the URI. It can be configured using both literal strings and regular expressions. To use regular expressions, you must use a prefix:

  1. “~” for case sensitive matching
  2. “~*” for case insensitive matching
  3. there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else.

The order in which location directives are checked is as follows:

  1. Directives with the “=” prefix that match the query exactly (literal string). If found, searching stops.
  2. All remaining directives with conventional strings. If this match used the “^~” prefix, searching stops.
  3. Regular expressions, in the order they are defined in the configuration file.
  4. If #3 yielded a match, that result is used. Otherwise, the match from #2 is used.

i want to block access to any script to member directory,but allow access to /member/a.php and /member/b.php.

Source code    
          listen       80;
          index index.html index.htm index.php default.html default.htm default.php;
          root  /html/;
          location ~ /member/(a|b)\.(php|php5)
                try_files $uri =404;
               include fastcgi.conf;
         location ~ /member/.*\.(php|php5)
               deny all;
         location ~ .*\.(php|php5)?$
                 try_files $uri =404;
                 fastcgi_index index.php;
                 include fastcgi.conf;
         location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
                 expires      30d;
         location ~ .*\.(js|css)?$
                 expires      12h;
Aug 05

linux – vi editor tutorial

This is a really good tutor from

There are many ways to edit files in Unix and for me one of the best ways is using screen-oriented text editor vi. This editor enable you to edit lines in context with other lines in the file.

Now a days you would find an improved version of vi editor which is called VIM. Here VIM stands for Vi IMproved.

The vi is generally considered the de facto standard in Unix editors because:

  • It’s usually available on all the flavors of Unix system.
  • Its implementations are very similar across the board.
  • It requires very few resources.
  • It is more user friendly than any other editors like ed or ex.

You can use vi editor to edit an existing file or to create a new file from scratch. You can also use this editor to just read a text file.

Starting the vi Editor:

There are following way you can start using vi editor:

Command Description
vi filename Creates a new file if it already does not exist, otherwise opens existing file.
vi -R filename Opens an existing file in read only mode.
view filename Opens an existing file in read only mode.

Following is the example to create a new file testfile if it already does not exist in the current working directory:

[amrood]$vi testfile

As a result you would see a screen something like as follows:

"testfile" [New File]

You will notice a tilde (~) on each line following the cursor. A tilde represents an unused line. If a line does not begin with a tilde and appears to be blank, there is a space, tab, newline, or some other nonviewable character present.

So now you have opened one file to start with. Before proceeding further let us understanding few minor but important concepts explained below.

Operation Modes:

While working with vi editor you would come across following two modes:

  1. Command mode: This mode enables you to perform administrative tasks such as saving files, executing commands, moving the cursor, cutting (yanking) and pasting lines or words, and finding and replacing. In this mode, whatever you type is interpreted as a command.
  2. Insert mode: This mode enables you to insert text into the file. Everything that’s typed in this mode is interpreted as input and finally it is put in the file .

The vi always starts in command mode. To enter text, you must be in insert mode. To come in insert mode you simply type i. To get out of insert mode, press the Esc key, which will put you back into command mode.

Hint: If you are not sure which mode you are in, press the Esc key twice, and then you’ll be in command mode. You open a file using vi editor and start type some characters and then come in command mode to understand the difference.

Getting Out of vi:

The command to quit out of vi is :q. Once in command mode, type colon, and ‘q’, followed by return. If your file has been modified in any way, the editor will warn you of this, and not let you quit. To ignore this message, the command to quit out of vi without saving is :q!. This lets you exit vi without saving any of the changes.

The command to save the contents of the editor is :w. You can combine the above command with the quit command, or :wq and return.

The easiest way to save your changes and exit out of vi is the ZZ command. When you are in command mode, type ZZ and it will do the equivalent of :wq.

You can specify a different file name to save to by specifying the name after the :w. For example, if you wanted to save the file you were working as another filename called filename2, you would type :w filename2 and return. Try it once.

Moving within a File:

To move around within a file without affecting your text, you must be in command mode (press Esc twice). Here are some of the commands you can use to move around one character at a time:

Command Description
k Moves the cursor up one line.
j Moves the cursor down one line.
h Moves the cursor to the left one character position.
l Moves the cursor to the right one character position.

There are following two important points to be noted:

  • The vi is case-sensitive, so you need to pay special attention to capitalization when using commands.
  • Most commands in vi can be prefaced by the number of times you want the action to occur. For example, 2j moves cursor two lines down the cursor location.

There are many other ways to move within a file in vi. Remember that you must be in command mode (press Esc twice). Here are some more commands you can use to move around the file:

Command Description
0 or | Positions cursor at beginning of line.
$ Positions cursor at end of line.
w Positions cursor to the next word.
b Positions cursor to previous word.
( Positions cursor to beginning of current sentence.
) Positions cursor to beginning of next sentence.
E Move to the end of Blank delimited word
{ Move a paragraph back
} Move a paragraph forward
[[ Move a section back
]] Move a section forward
n| Moves to the column n in the current line
1G Move to the first line of the file
G Move to the last line of the file
nG Move to nth line of the file
:n Move to nth line of the file
fc Move forward to c
Fc Move back to c
H Move to top of screen
nH Moves to nth line from the top of the screen
M Move to middle of screen
L Move to botton of screen
nL Moves to nth line from the bottom of the screen
:x Colon followed by a number would position the cursor on line number represented by x

Control Commands:

There are following useful command which you can use along with Control Key:

Command Description
CTRL+d Move forward 1/2 screen
CTRL+d Move forward 1/2 screen
CTRL+f Move forward one full screen
CTRL+u Move backward 1/2 screen
CTRL+b Move backward one full screen
CTRL+e Moves screen up one line
CTRL+y Moves screen down one line
CTRL+u Moves screen up 1/2 page
CTRL+d Moves screen down 1/2 page
CTRL+b Moves screen up one page
CTRL+f Moves screen down one page
CTRL+I Redraws screen

Editing Files:

To edit the file, you need to be in the insert mode. There are many ways to enter insert mode from the command mode:

Command Description
i Inserts text before current cursor location.
I Inserts text at beginning of current line.
a Inserts text after current cursor location.
A Inserts text at end of current line.
o Creates a new line for text entry below cursor location.
O Creates a new line for text entry above cursor location.

Deleting Characters:

Here is the list of important commands which can be used to delete characters and lines in an opened file:

Command Description
x Deletes the character under the cursor location.
X Deletes the character before the cursor location.
dw Deletes from the current cursor location to the next word.
d^ Deletes from current cursor position to the beginning of the line.
d$ Deletes from current cursor position to the end of the line.
D Deletes from the cursor position to the end of the current line.
dd Deletes the line the cursor is on.

As mentioned above, most commands in vi can be prefaced by the number of times you want the action to occur. For example, 2x deletes two character under the cursor location and 2dd deletes two lines the cursor is on.

I would highly recommend to exercise all the above commands properly before proceeding further.

Change Commands:

You also have the capability to change characters, words, or lines in vi without deleting them. Here are the relevant commands:

Command Description
cc Removes contents of the line, leaving you in insert mode.
cw Changes the word the cursor is on from the cursor to the lowercase w end of the word.
r Replaces the character under the cursor. vi returns to command mode after the replacement is entered.
R Overwrites multiple characters beginning with the character currently under the cursor. You must use Esc to stop the overwriting.
s Replaces the current character with the character you type. Afterward, you are left in insert mode.
S Deletes the line the cursor is on and replaces with new text. After the new text is entered, vi remains in insert mode.

Copy and Past Commands:

You can copy lines or words from one place and then you can past them at another place using following commands:

Command Description
yy Copies the current line.
yw Copies the current word from the character the lowercase w cursor is on until the end of the word.
p Puts the copied text after the cursor.
P Puts the yanked text before the cursor.

Advanced Commands:

There are some advanced commands that simplify day-to-day editing and allow for more efficient use of vi:

Command Description
J Join the current line with the next one. A count joins that many lines.
<< Shifts the current line to the left by one shift width.
>> Shifts the current line to the right by one shift width.
~ Switch the case of the character under the cursor.
^G Press CNTRL and G keys at the same time to show the current filename and the status.
U Restore the current line to the state it was in before the cursor entered the line.
u Undo the last change to the file. Typing ‘u’ again will re-do the change.
J Join the current line with the next one. A count joins that many lines.
:f Displays current position in the file in % and file name, total number of file.
:f filename Renames current file to filename.
:w filename Write to file filename.
:e filename Opens another file with filename.
:cd dirname Changes current working directory to dirname.
:e # Use to toggle between two opened files.
:n In case you open multiple files using vi, use :n to go to next file in the series.
:p In case you open multiple files using vi, use :p to go to previous file in the series.
:N In case you open multiple files using vi, use :N to go to previous file in the series.
:r file Reads file and inserts it after current line
:nr file Reads file and inserts it after line n.

Word and Character Searching:

The vi editor has two kinds of searches: string and character. For a string search, the / and ? commands are used. When you start these commands, the command just typed will be shown on the bottom line, where you type the particular string to look for.

These two commands differ only in the direction where the search takes place:

  • The / command searches forwards (downwards) in the file.
  • The ? command searches backwards (upwards) in the file.

The n and N commands repeat the previous search command in the same or opposite direction, respectively. Some characters have special meanings while using in search command and preceded by a backslash (\) to be included as part of the search expression.

Character Description
^ Search at the beginning of the line. (Use at the beginning of a search expression.)
. Matches a single character.
* Matches zero or more of the previous character.
$ End of the line (Use at the end of the search expression.)
[ Starts a set of matching, or non-matching expressions.
< Put in an expression escaped with the backslash to find the ending or beginning of a word.
> See the ‘<’ character description above.

The character search searches within one line to find a character entered after the command. The f and F commands search for a character on the current line only. f searches forwards and F searches backwards and the cursor moves to the position of the found character.

The t and T commands search for a character on the current line only, but for t, the cursor moves to the position before the character, and T searches the line backwards to the position after the character.

Set Commands:

You can change the look and feel of your vi screen using the following :set commands. To use these commands you have to come in command mode then type :set followed by any of the following options:

Command Description
:set ic Ignores case when searching
:set ai Sets autoindent
:set noai To unset autoindent.
:set nu Displays lines with line numbers on the left side.
:set sw Sets the width of a software tabstop. For example you would set a shift width of 4 with this command: :set sw=4
:set ws If wrapscan is set, if the word is not found at the bottom of the file, it will try to search for it at the beginning.
:set wm If this option has a value greater than zero, the editor will automatically “word wrap”. For example, to set the wrap margin to two characters, you would type this: :set wm=2
:set ro Changes file type to “read only”
:set term Prints terminal type
:set bf Discards control characters from input

Running Commands:

The vi has the capability to run commands from within the editor. To run a command, you only need to go into command mode and type :! command.

For example, if you want to check whether a file exists before you try to save your file to that filename, you can type :! ls and you will see the output of ls on the screen.

When you press any key (or the command’s escape sequence), you are returned to your vi session.

Replacing Text:

The substitution command (:s/) enables you to quickly replace words or groups of words within your files. Here is the simple syntax:


The g stands for globally. The result of this command is that all occurrences on the cursor’s line are changed.


Here are the key points to your success with vi:

  • You must be in command mode to use commands. (Press Esc twice at any time to ensure that you are in command mode.)
  • You must be careful to use the proper case (capitalization) for all commands.
  • You must be in insert mode to enter text.
Aug 04

zen cart – .htaccess file to protect images,cache,bmz_cache folder from attact

To compatible with most 3rd application,most server has a common configuration.This lead to some potential security problem.Zen car allow globally read and write to its images,bmz_cache,cache directory.

The following .htaccess config will help to disable the index list of image directory, block any attemp to running script from this can put this .htaccess in the zen cart images directory for better security.

Source code    

# deny *everything*
<FilesMatch ".*">
  Order Allow,Deny
  Deny from all
# but now allow just *certain* necessary files:
<FilesMatch ".*\.(jpe?g|JPE?G|gif|GIF|png|PNG|swf|SWF)$" >
  Order Allow,Deny
  Allow from all
OPTIONS -Indexes -ExecCGI

The .htaccess above blocks direct HTTP requests to all filetypes in this directory recursively, except certain approved exceptions(image and other approved static file). It also prevents the ability of any scripts to run. No type of script, be it PHP, PERL or whatever, can normally be executed if ExecCGI is disabled.This Will also prevent people from seeing what is in the dir. and any sub-directories. We’d better put this file to both images and bmz_image directory.

For the cache directory,we need to block running script and disalbe auto the .htaccess can be:

Source code    
# deny *everything*
<FilesMatch ".*">
  Order Allow,Deny
  Deny from all
OPTIONS -Indexes -ExecCGI
Aug 03

apache – globally disable direcory browsing

Zen cart website have some special folder which allow read write from apache user.This may be a potential security problem.Below is a list of folder we are talking about:

|– bmz_cache
|– cache
|– cgi-bin
|– download
|– editors
|– email
|– images
|– includes
|– media
|– pub
|– tempEP

The folder list above is the output from the command below of a zen cart website:

Source code    
tree -d -L 1

Those such directory should not be access directly from the web.but most server config make it possible.As there is no index.php file in those such directory,the apache server may return a index list of file in that directory for all request to the directory without any specified file.For example,a request to or will get response with a index list of cache and bmz_cache directory content respectively. So for the security purpose,we need to turn of the auto index feature of apache.

Of course we can put .htaccess file  in the directory to disable auto index,

Source code    
Options -Indexes

but in this way we will need to create many .htaccess for all directory in all zen cart to globally disable directory list(auto index) from apache.

Source code    
<Directory />
    Options FollowSymLinks
    AllowOverride None


Source code    
<Directory />
    Options FollowSymLinks -Indexes
    AllowOverride All

Both config will work.but the second config is more flexible, as you can change config for some directory but keep other unchanged.and zen cart need .htaccesss for seo and some other purpose.


Aug 02

zen cart — Can’t create/write to file ‘/tmp/ (Errcode: 30)

one zen cart website’s front page got corrupted,the error message looks like:
Can’t create/write to file ‘/tmp/#sql_ .MYI’ (Errcode: 30)
i tried to restart mysql server with

Source code    
/etc/init.d/mysqld restart

but the problem still no solved

i found that the zen cart backend home page is ok from i tried to repair the table according to the error message,but still no.

after a while search,i got the solution as below:

It is likely that your /usr/tmpDSK is corrupted. You should stop all processes that have files open on /tmp such as MySQL and other applications using:

lsof /tmp

Run the following commands (in that order):

Source code    
/bin/umount -l /tmp    #umount tmp
/bin/umount -l /var/tmp # umount /var/tmp
/bin/rm -fv /usr/tmpDSK # remove /usr/tmpDSK

/scripts/securetmp  #recreate
This should create a new /tmp partition for you. That’s all .This will take a while to run.and keep in mind that only server with Cpanel  have  /scripts/securetmp script.You will have to recreate yourself if you are not running Cpanel.
Someone says restart the system sometimes fixes the problem.


Jul 31

linux – the meaning of the cpu summary info from top command

Cpu(s): 0.0%us, 0.0%sy, 0.0%ni,100.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
What does these things mean? Here is a small explanation for each section :-

  1. us -> User CPU time: The time the CPU has spent running users’ processes that are not niced.
  2. sy -> System CPU time: The time the CPU has spent running the kernel and its processes.
  3. ni -> Nice CPU time: The time the CPU has spent running users’ proccess that have been niced.
  4. wa -> iowait: Amount of time the CPU has been waiting for I/O to complete.
  5. hi -> Hardware IRQ: The amount of time the CPU has been servicing hardware interrupts.
  6. si -> Software Interrupts.: The amount of time the CPU has been servicing software interrupts.
  7. id is idle, in other words CPU idle status
  8. st is Time stolen from a virtual machine. Prior to Linux 2.6.11, unknown

This shows a breakup of CPU usage, depending on your servers role, you need to optimize it. If you have a lot of disk writing keep a watch on iowait. If might be wondering what does “The time the CPU has spent running users’ processes that are not niced.” mean? If you do a “man nice”, it will say “nice – run a program with modified scheduling priority“. It is called “nice” because the number that is given to a process determines how willing a task is to step aside and let other tasks monopolize the processor. The number varies from -20 to 19. The default value is 0, higher values lower the priority and lower values increase it. If you want to read more about nice, visit

Jul 25

javascript – how to add/remove css class from a dom element

To change css style of a dom element,we usually operate directly on the style property of the element.for example:

document.getElementById('Id'').style.visibility = "visible";

what if we don’t want to operate in this way,we need to apply a list of css rule to the this case,we just need to specify a new css class for the element.

document.getElementById('Id'').class = "newClass";

The code above will not work at all.

document.getElementById('Id').className = "newClass";

The code above will set the className to newClass.To only add or remove,the code will be a little more:

Source code    
document.getElementById("MyElement").className += " MyClass";
Source code    
document.getElementById("MyElement").className =
      ( /(?:^|\s)MyClass(?!\S)/ , '' )

or we can just

Source code    
Jul 25

grep – how to use grep command

First,let’s take a look at the example,

Source code    
grep -rn 'order->info\[' .

This grep command search recursively in the current directory for all files which containing the string order->info[ . From this example, we  know:
-r option instruct grep to search recursively in all directory and sub-directory.
with -n option, grep will output the number of the line in the text file from which it was matched.
and what's more, the special character need to be escaped. like the [ character.

Source code    
grep -c 'word' /path/to/file

The command above with -c optionwill count how many times the word was matched in the specified file.
To let grep to ignore case while searching, we need to add -i option,so we can adapt the above command to be:

Source code    
grep -ic 'word' /path/to/file

From grep command's man page,we can get more detail:
--color option will hep to highlight the matched string in the out with color(defined by GREP_OPTIONS environment variables)
-v option will invert the grep (output/action) result. by default,grep will print only the matched lines.with -v option,it will only print those lines that do not matched.
-I  option process a binary file as if it did not contain matching data; that is not to process the binary file(i think so)
-m the max time matched. grep will stop searching after specified time match.
-E work together with -e option,treat the string as a as an extended regular expression.Keep in mind that -e option is not necessary if the pattern(search string) not start with -.Let's take a look at the following example:

Source code    
grep -E 'DIR_WS_IMAGES|DIR_WS_INCLUDES' includes/configure.php

search both two string in the the pattern not start with -,so -e option can be omitted.
Now comes the last three option i would like to introduce:
-A NUM print NUM line of trailing context after matching lines.
-B NUM Print NUM lines of leading context before matching lines.
-C NUM Print NUM lines of output context.

Source code    
grep /home/oakleysu/ -m 1 -B 5 /usr/local/apache/conf/httpd.conf


Well,grep is really powerful and helpful in linux server admin and programming.but this post is just my own opinion on using grep to help in my work. you can take a look at the man page to get more info.


Jul 23

linux – how to strip leading components from file names before extraction tar ball

just in case you meet the following problem:

we have a tar ball source.tar.gz containing the following files,


you only need to extract all php file to current directory,you don’t need any other directory from the tar the other words,you do not want to keep the leading directory structure,but only the content to do that.yes,you can just extract it and do some mv and rm fact tar has a builtin option which can strip components from file name before extraction,it’s the –strip-components NUMBER, –strip-path you can do that with the following command:

Source code    
tar -xvzf surce.tar.gz  --strip-components  3

pls be noted tar-1.14 uses –strip-path and tar-1.14.90+ uses –strip-components.

Jul 20

zen cart — sort the product attribute option value

With the help of zen cart easy populate module,we can easy import products to zen cart store.however,the problem come when we tried to import attribute data(size,color etc.).we don’t know how to specified the attribute option order.and we don’t want to specify order for each attribute option.why not just sort the arribute option by its id.then in the product view page,the attribute’s option will be listed in the same order as the data sheet we imported.To implement this feature,we just need to make a change as below:
—- includes/modules/attributes.php

Source code    
//change the $order_by  variable
$order_by = ' order by pov.products_options_values_id';
while (!$products_options_names->EOF) {
    $products_options_array = array();
    pa.options_values_price, pa.price_prefix,
    pa.products_options_sort_order, pa.product_attribute_is_free, pa.products_attributes_weight, pa.products_attributes_weight_prefix,
    pa.attributes_default, pa.attributes_discounted, pa.attributes_image
    $sql = "select    pov.products_options_values_id,
  where     pa.products_id = '" . (int)$_GET['products_id'] . "'
  and       pa.options_id = '" . (int)$products_options_names->fields['products_options_id'] . "'
  and       pa.options_values_id = pov.products_options_values_id
  and       pov.language_id = '" . (int)$_SESSION['languages_id'] . "' " .
    $products_options = $db->Execute($sql);