GET
PUT
POST
DELETE
HEAD
JSONP
пятница, 14 июня 2013 г.
пятница, 29 марта 2013 г.
Apache Help
Important Apache Directives
Directive Default Value Alternative Example Location
ServerRoot /usr/local/apache /etc/httpd
ErrorLog <ServerRoot>/logs/error_log /etc/httpd/logs/errors
DocumentRoot <ServerRoot>/htdocs /home/httpd/public_html
--------------------------------------------------------------------------------
User nobody (Unix Only)
Group nobody (Unix Only)
ServerType standalone
ServerRoot /usr/local/apache (Where Apache folder? The server root is where Apache keeps all its essential files.)
ServerName www.alpha-complex.com (Site URL)
ServerAdmin administrator@email.com (Admin Email)
Listen 80 (Listen only coonections on this IP and Port)
Listen 443
Listen 127.0.0.1:80
Listen 127.0.0.1:443
Listen 192.168.1.1:80
Listen 192.168.1.1:443
ErrorLog /usr/local/apache/logs/error_log (Default Error Log)
TransferLog /logs/access_log (Also known as Access Log)
DocumentRoot htdocs (Where all site files? Default folder for all site files.)
DocumentRoot /usr/local/apache/htdocs
--------------------------------------------------------------------------------
Base Master Configuration File
httpd.conf:
ServerName www.alpha-complex.com
Listen 192.168.1.1:80
Listen 192.168.1.1:443
User nobody
Group nobody
ServerAdmin webmaster@alpha-complex.com
#ServerRoot /usr/local/apache
#ErrorLog logs/error_log
TransferLog logs/access_log
DocumentRoot /home/www/alpha-complex
--------------------------------------------------------------------------------
# Load Apache modules
LoadModule vhost_alias_module libexec/mod_vhost_alias.so
...
LoadModule setenvif_module libexec/mod_setenvif.so
--------------------------------------------------------------------------------
# Virtual host directives
<VirtualHost 192.168.1.1>
Include conf/virtualhost.conf
Include conf/intranet_one.conf
Include /etc/httpd/conf/*.conf
Include /etc/httpd/conf/networks/*.conf
Include /etc/httpd/conf/[0-9][0-9]_*.conf
</VirtualHost>
<VirtualHost 192.168.10.1>
Include conf/virtualhost.conf
Include conf/intranet_ten.conf
</VirtualHost>
<VirtualHost 204.148.170.4>
Include conf/virtualhost.conf
Include conf/extranet.conf
</VirtualHost>
<VirtualHost www.beta-complex.com>
User beta
Group betausers
...
</VirtualHost>
<VirtualHost 204.148.170.3>
ServerName www.alpha-complex.com
ServerAlias alpha-complex.com *.alpha-complex.com
ServerAdmin webmaster@alpha-complex.com
DocumentRoot /home/www/alpha-complex
ErrorLog logs/alpha-complex_errors
TransferLog logs/alpha-complex_log
</VirtualHost>
<VirtualHost 204.148.170.3:80>
# virtual host directives
...
<Location />
RemoveHandler .shtml
<Location>
</VirtualHost>
# SSL configuration directives
SSLEngine off
<VirtualHost 204.148.170.7:443>
# virtual host directives
...
SSLEngine on
</VirtualHost>
Listen 443
Listen 80
# server level directives
...
<VirtualHost 204.148.170.3:*>
ServerName www.alpha-complex.com
AssignUserID alphabadm alphagroup
# virtual host directives
...
</VirtualHost>
<VirtualHost 204.148.170.4:80>
ServerName www.beta-complex.com:80
AssignUserID betavadm betagroup
# virtual host directives
...
</VirtualHost>
<VirtualHost 204.148.170.5:443>
ServerName secure.troubleshooter.com:443
AssignUserID primeuadm alphagroup
SSLEngine on
# virtual host directives
...
</VirtualHost>
<VirtualHost 204.148.170.5>
ServerName users.alpha-complex.com
# virtual host directives
...
</VirtualHost>
<VirtualHost 204.148.170.5>
ServerName secure.alpha-complex.com
# virtual host directives
...
</VirtualHost>
<VirtualHost 204.148.170.5>
ServerName www.alpha-complex.com
# virtual host directives
...
</VirtualHost>
<VirtualHost 204.148.170.3>
ServerName www.alpha-complex.com
ServerAlias www.alpha-prime.com *complex*.???
ServerAdmin ...
DocumentRoot ...
ErrorLog ...
TransferLog ...
</VirtualHost>
<VirtualHost 204.148.170.3:*>
ServerName www.alpha-complex.com:80
ServerAlias *
RewriteEngine On
RewriteRule .* - [R]
</VirtualHost>
<VirtualHost 204.148.170.5 204.148.170.7:443>
# this name resolves to 204.148.170.7
ServerName secure.alpha-complex.com:443
# this alias matches hosts on the name-based IP
ServerAlias secure.*
ServerAdmin secure@alpha-complex.com
DocumentRoot /home/www/alpha-complex/
ErrorLog logs/alpha-complex_sec_error
TransferLog logs/alpha-complex_sec_log
# this assumes we've specified the other SSL directives elsewhere
<Location /secure/>
SSLEngine on
</Location>
</VirtualHost>
<VirtualHost 204.148.170.3>
ServerName server1.alpha-complex.com
ServerAdmin webmaster@alpha-complex.com
ServerAlias server[0-9].alpha-complex.com
VirtualDocumentRoot /home/www/%1.1+.alpha-complex/web/
VirtualScriptAlias /home/www/%1.1+.alpha-complex/cgi-bin/
ErrorLog logs/alpha-complex_error
TransferLog logs/alpha-complex_log
</VirtualHost>
--------------------------------------------------------------------------------
# Local Apache customizations.
# set additional/conditional environment variables.
Include /etc/httpd/conf/Env.conf
# IP, Host, and URL based access restrictions.
Include /etc/httpd/conf/Access.conf
# mod_perl configuration.
Include /etc/httpd/conf/Perl.conf
# All-sites directory configuration.
Include /etc/httpd/conf/Sites.conf
# Virtual hosts
Include /etc/httpd/conf/Vhost.conf
--------------------------------------------------------------------------------
AccessFileName .access .config .perdirectory (The AccessFileName directive causes Apache to look for files called .access, .config,
and .perdirectory and parse them in the order specified)
--------------------------------------------------------------------------------
Container Directives
# <VirtualHost> (<VirtualHost> allows additional hosts and Web sites to be defined alongside the main server host site. Each virtual host can have its
own name, IP address, and error and access logs.)
<VirtualHost 192.168.1.2>
ServerName www.beta-complex.com
ServerAdmin troubleshooter@beta-complex.com
CustomLog /logs/beta_access_log common
TransferLog /logs/beta_access_log
ErrorLog /logs/beta_error_log
DocumentRoot /home/www/beta-complex
</VirtualHost>
# <Directory> (For all files in this directory)
<Directory />
AuthType Basic
AuthUserFile /usr/local/apache/auth/password.file
</Directory>
<Directory />
Options none
AllowOverride none
order allow,deny
deny from all
</Directory>
<Directory /home/www/alpha-complex>
Options Includes FollowSymLinks
AllowOverride FileInfo
allow from all
</Directory>
<Directory /home/www/*>
AllowOverride All
</Directory>
# <DirectoryMatch> (<DirectoryMatch> is for specifying regular expressions instead of wildcards in the directory specification)
<DirectoryMatch "/[A-Z][0-9]{2}/">
AllowOverride All
</DirectoryMatch>
# <Files>(<Files> are similar to <Directory> but match files instead.)
<Directory /home/www/alpha-complex/gallery>
<Files *.gif>
SetHandler /cgi-bin/burn-gifs.cgi
</Files>
</Directory>
# <FilesMatch> (<FilesMatch> is for specifying regular expressions instead of wildcards in the file’s specification.)
<Directory /home/www/alpha-complex/wanted/mugshots>
<FilesMatch "\.(gif|jpg)$">
SetHandler /cgi-bin/process-image.cgi
</Files>
</Directory>
# <Location> (<Location> operates in a similar manner to <Directory> but applies to a URL rather than a physical file location.)
<Location /server-info>
SetHandler server-info
</Location>
<Location /secure/administrators>
AuthName "Administrator's Area"
require user administrator
</Location>
<Location /secure/members>
AuthName "Members Only"
require valid-user
</Location>
# <LocationMatch> (<LocationMatch> is for specifying regular expressions instead of wildcards in the location specification.)
<LocationMatch "^/[A-Z][a-z]+/$">
SetHandler server-info
</LocationMatch>
<Location /secure-area>
order deny, allow
deny from all
allow from 192.168.1.100
allow from 192.168.1.101
</Location>
<Location /secure-area>
order deny, allow
deny from all
allow from 192.168.1.100
allow from 192.168.1.101
Satisfy all
AuthName "Secure Area"
AuthType Basic
AuthUserFile /usr/local/apache/auth/password.file
require valid-user
</Location>
--------------------------------------------------------------------------------
Alias /doc /usr/doc
Alias /icons/ /usr/local/apache/icons/
Alias /icons/ /usr/local/images/alternative-icons/
--------------------------------------------------------------------------------
• Options: The Options directive controls how Apache regards the file system. It
takes one or more options as parameters, each of which modifies how the server
behaves on encountering a particular situation such as an executable file, a
symbolic link, or a directory that contains no default index page.
• AllowOverride: The AllowOverride directive controls which directives can be
placed in per-directory .htaccess files to override the server configuration,
including the Options directive.
--------------------------------------------------------------------------------
Options All None ExecCGI FollowSymLinks SymLinksIfOwnerMatch Includes IncludesNOEXEC Indexes MultiViews
Options Indexes Includes
Options FollowSymLinks
<Location />
Options -Indexes
</Location>
<Location /ftp/>
Options +Indexes
</Location>
All - Enables all options except for MultiViews.
ExecCGI - Permits execution of CGI scripts.
FollowSymLinks - Files or directories referred to via symbolic links will be followed. Has no effect inside <Location> containers.
SymLinksIfOwnerMatch - The server will only follow symbolic links for which the target file or directory is owned by the same user ID as the link.
Includes - Permits Server-Side Includes (SSIs).
IncludesNOEXEC - Permits Server-Side Includes but limits execution of CGI scripts.
Indexes - If a URL that maps to a directory is requested, and there’s no corresponding index file identified with the DirectoryIndex directive, Apache will create and return a formatted listing of the directory contents, controlled by the IndexOptions directive,
MultiViews - Content-negotiated MultiViews are allowed. This option isn’t enabled by the use of All.
None - Disables all options.
--------------------------------------------------------------------------------
Options Modifiers
Position Modifier
Grandparent Options Indexes Includes FollowSymLinks
Parent Options +ExecCGI –Indexes
Directory Options -Includes +IncludesNoExec
Result Options FollowSymLinks ExecCGI IncludesNoExec
--------------------------------------------------------------------------------
AllowOverride All None FileInfo Limit AuthConfig
<Directory />
AllowOverride None
</Directory>
<Location />
AllowOverride All
</Location>
--------------------------------------------------------------------------------
• order deny,allow: Implements a restrictive access policy where most hosts are
denied and then a smaller subset given access
• order allow,deny: Implements a permissive access policy where most hosts are
allowed and then a smaller subset refused access
allow from crawler.beta-complex.com
deny from .beta-complex.com
# traditional partial IP address
allow 192.168
# network address and netmask
allow 192.168.0.0/255.255.0.0
# network address and bitmask
allow 192.168.0.0/16
<Directory />
order deny,allow
deny from all
allow from localhost
</Directory>
<Directory />
order allow,deny
allow from all
deny from robot.trouble.com
</Directory>
<Directory />
order deny,allow
deny from .trouble.com
allow from no.trouble.com little.trouble.com
</Directory>
<Directory /internal-eyes-only/>
order deny,allow
deny from all
allow from 127.0.0.1 192.168.1 192.168.2
</Directory>
<Directory /my-ipv6-eyes-only/>
order deny,allow
deny from all
allow from fe80::910:a4ff:aefe:9a8, 127.0.0.1
</Directory>
<Directory /no-indexing-here/>
order allow,deny
allow from all
# 101.202.85.5 is the IP for robot.trouble.com...
deny from robot.trouble.com 101.202.68.5
</Directory>
BrowserMatch ^Mozilla lizards_rule
<Directory /mozilla-area/>
order deny,allow
deny from all
allow from env=lizards_rule
</Directory>
SetEnvIf Request_Protocol ^HTTP/1.1 http_11_ok
<Directory /http11only/>
order deny,allow
deny from all
allow from env=http_11_ok
</Directory>
SetEnvIf Referer ^http://www.alpha-prime.com/secure/links_page.html origin_ok
<Directory /alphaprime_users_only/>
order deny,allow
deny from all
allow from env=origin_ok
</Directory>
<Location /registered-users-only/>
# allow only registered users access
AuthName "Registered Users Only"
AuthType Basic
AuthDBMUserFile /usr/local/apache/auth/password.dbm
require valid-user
# lock out external clients
order deny,allow
deny from all
allow from 192.168.1 192.168.2
# allow either access method
Satisfy any # or Satisfy all
</Location>
--------------------------------------------------------------------------------
<Directory /ftp/>
Options +Indexes
IndexOrderDefault Ascending Name
# IndexOrderDefault Ascending Size
# IndexOrderDefault Descending Date
IndexIgnore .??* *~ *# *.bak HEADER* README* SCCS RCS
DirectoryIndex index.html
DirectoryIndex index.html index.htm index.shtml home.html home.htm index.cgi
</Directory>
--------------------------------------------------------------------------------
BrowserMatch Mozilla lizard=true
SetEnvIf User-Agent Mozilla lizard=true
BrowserMatch .*spider.* is_a_robot robot=spider !give_access
# test for HTTP/1.0 and HTTP/1.1 requests
SetEnvIf Request_Protocol ^HTTP/1.1 http_proto=11
SetEnvIf Request_Protocol ^HTTP/1.0 http_proto=10
# test for environment variable 'http_proto' - if unset assume HTTP/0.9
SetEnvIf http_proto !^1 http_proto=09
BrowserMatchNoCase crawler robot
BrowserMatchNoCase yahoo robot=yahoo
BrowserMatchNoCase infoseek robot=infoseek
BrowserMatchNoCase spider robot
BrowserMatchNoCase spyder robot
BrowserMatchNoCase bot robot
BrowserMatchNoCase harvest robot=harvest
BrowserMatchNoCase crawler robot=crawler
BrowserMatchNoCase yahoo robot=yahoo
--------------------------------------------------------------------------------
RewriteCond %{HTTP_USER_AGENT} .*robot.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} .*crawler.* [NC,OR]
RewriteCond %{REMOTE_HOST} badrobot.com$ [NC]
RewriteRule ^/not-indexable/ - [F]
--------------------------------------------------------------------------------
TypesConfig conf/mime.types
Content-Type: image/gif
text/html html htm
text/plain asc txt
text/sgml sgml sgm
image/jpeg jpeg jpg jpe
image/gif gif
image/png png
application/x-javascript js
application/pdf pdf
application/postscript ai eps ps
audio/mpeg mpga mp2 mp3
video/quicktime qt mov
AddType application/x-mylanguage .myl .mylanguage
AddType text/mylanguage myl mylanguage
AddType text/svg+xml .svg
DefaultType text/html
--------------------------------------------------------------------------------
AddEncoding x-gzip .gz
AddEncoding x-compress .Z
AddEncoding zip .zip
AddEncoding mac-binhex40 .hqx
AddEncoding zip zip
Content-Type: text/html
Content-Encoding: zip
<Directory /home/sites/alpha-complex/encoded>
AddEncoding x-gzip gz
<Files *.gz.html>
RemoveEncoding gz
</Files>
<FilesMatch \.gz$>
AddEncoding x-gzip gz
</FilesMatch>
</Directory>
<Directory /mixed/html/and/images>
SetOutputFilter Deflate
<FilesMatch \.(gif|jpg|png)$>
SetEnv no-gzip
</Files>
</Directory>
<Directory /mixed/html/and/images>
SetOutputFilter Deflate
<FilesMatch \.(gif|jpg|png)$>
SetEnv no-gzip all-browsers
</Files>
BrowserMatch ^Mozilla/4 no-gzip
BrowserMatch " MSIE" !no-gzip
Header append Vary User-Agent env=!all-browsers
</Directory>
--------------------------------------------------------------------------------
Content-Language: en
DefaultLanguage en
AddLanguage en .en .english
AddLanguage de .de .deutsch .german
LanguagePriority en de fr
<Directory /deutsch/>
DefaultLanguage de
</Directory>
<Directory /deutsch/>
<Files *.html>
DefaultLanguage de
</Files>
</Directory>
--------------------------------------------------------------------------------
Content-type: text/html; charset=ISO-8859-1
AddCharSet ISO-8859-7 .gr .greek .latin7
AddDefaultCharset ISO-8859-7
AddType text/html;charset=ISO-8859-7 .grhtml
AddDefaultCharset on
<Location /images>
# our images don't contain text so we don't want or need a charset
AddDefaultCharset off
</Location>
<Location /images/buttons/greek>
AddDefaultCharset ISO-8859-7
</Location>
--------------------------------------------------------------------------------
RewriteEngine on
<Location /type-mapped-files>
AddHandler type-map .var
RewriteRule ^(.*\.html)$ $1.var [NS]
</Location>
AliasMatch ^/(type-mapped-files/.*\.html)$ /home/sites/alpha-compex/$1.var
<Location /type-mapped-files>
AddHandler type-map .var
</Location>
--------------------------------------------------------------------------------
Alias
Alias /images/ /home/gallery/photos/
AliasMatch /images/(.*)\.gif$ /usr/local/apache/images/$1.gif
AliasMatch /(.*)/images/(.*)\.gif$ /usr/local/apache/images/$1/$2.gif
AliasMatch ^(.*).logo$ /cgi-bin/logo-parser?$1.logo
ScriptAlias /cgi-bin/ /usr/local/apache/cgibin/
ScriptAliasMatch ^/cgi-bin/(.*)\.cgi$ /usr/local/apache/cgibin/$1.cgi
--------------------------------------------------------------------------------
Basic Redirection
Redirect permanent /archive http://archive.alpha-prime.com/archive/alpha-complex
Redirect permanent /archive http://archive.alpha-prime.com/archive/alpha-complex?querystring=new
permanent 301 - The requested resource has been assigned a new permanent URI, and any future references to this resource should use the returned URL.
temp 302 - The requested resource resides temporarily under a different URI.
seeother 303 - The response to the request can be found under a different URL and should be retrieved using a GET method, irrespective of the HTTP method used for the original request.
gone 410 - The requested resource is no longer available.
Use Proxy 305 - The requested resource must be retrieved through the proxy server given by the URL. The client then reissues the request to the proxy.
Temporary Redirect 307 - Many clients interpret a 302 response as if it were a 303 response and change the request method to GET, in violation of the HTTP/1.1 specification. To avoid this, 307 can be used to inform the client unambiguously that the new URL should be requested with the same HTTP method as the original.
--------------------------------------------------------------------------------
Redirection with Regular Expressions
RedirectMatch (.*)\.(gif|jpg)$ http://images.alpha-complex.com/imagecache/$1.$2
RedirectMatch 305 \.(gif|jpg)$ http://proxy.alpha-prime.com
--------------------------------------------------------------------------------
LoadModul rewrite_module modules/mod_rewrite.so
RewriteEngine on
RewriteRule /images/(.*)\.gif$ /usr/local/apache/images/$1.gif
RewriteRule /abcde/(.*) /12345/$1
RewriteRule /12345/(.*) /fghijk/$1
RewriteRule /abcde/(.*) /fghijk/\$1=$1
RewriteRule ^(.*)$ http://alpha-complex.com/$1
# define our list of trusted hosts
RewriteCond %{REMOTE_ADDR} ^192\.168\..* [OR]
RewriteCond %{REMOTE_ADDR} ^127\.0\.0\.1 [OR]
RewriteCond %{REMOTE_HOST} ^trusted.comrade.com$
# if the above conditions hold, don't touch the URL at all and skip the next rule
RewriteRule .* - [S=1]
# otherwise, redirect the client to the homepage
RewriteRule .* /index.html [R]
# we could rewrite the URL from the trusted hosts further here...
# a server-level rewrite rule
RewriteRule /abcde/(.*) /12345/$1
<Directory /container>
RewriteRule /12345/(.*) /fghijk/$1
# the server-level rewrite rule is not inherited here
</Directory>
<Directory /inherited/here>
# server-level Rewrite rule applies here
RewriteOptions inherit
</Directory>
<Directory /container/inherited/here>
# both RewriteRule directives apply here
RewriteOptions inherit
</Directory>
--------------------------------------------------------------------------------
RewriteCondVariables
Functionality Variable Name
Server internals DOCUMENT_ROOT, SERVER_ADMIN, SERVER_NAME, SERVER_ADDR, SERVER_PORT, SERVER_PROTOCOL, SERVER_SOFTWARE HTTP request REMOTE_ADDR, REMOTE_HOST, REMOTE_USER, REMOTE_IDENT, REQUEST_METHOD, SCRIPT_FILENAME, PATH_INFO, QUERY_STRING, AUTH_TYPE
HTTP headers HTTP_USER_AGENT, HTTP_REFERER, HTTP_COOKIE, HTTP_FORWARDED, HTTP_HOST, HTTP_PROXY_CONNECTION, HTTP_ACCEPT
Time TIME_YEAR, TIME_MON, TIME_DAY, TIME_HOUR, TIME_MIN, TIME_SEC, TIME_WDAY, TIME
Specials API_VERSION, THE_REQUEST, REQUEST_URI, REQUEST_FILENAME, IS_SUBREQ
--------------------------------------------------------------------------------
SSI Server Side Includes
Enable SSI
Options +Includes
# allow static content to be included, but do not run CGIs
Options +IncludesNOEXEC
<Location /ssidocs>
Options +Includes
</Location>
<Location />
AddHandler server-parsed .shtml
</Location>
<Location /include>
SetHandler server-parsed
</Location>
AddHandler server-parsed .shtml .html .htm
<Location /ssi-cgibin>
Options +ExecCGI +Includes
AllowOverride None
AddHandler cgi-script .cgi
AddOutputFilter Includes .cgi
</Location>
Format of SSI Commands
<!--#command parameter="value" parameter="value" ... -->
<!--#include virtual="/include/$1" -->
<!--#set var="CLEARED_TITLE" value="Welcome, Troubleshooter" -->
<!--#set var="UNCLEARED_TITLE" value="You are not cleared to read this document" -->
<!--#if expr="${CLEARED}" -->
<!--#set var="TITLE” value="CLEARED_TITLE" -->
<!--#else -->
<!--#set var="TITLE" value="UNCLEARED_TITLE" -->
<!--#endif -->
<!--#echo var="$TITLE" -->
--------------------------------------------------------------------------------
CGI
ScriptAlias /cgi-bin/ "/usr/local/apache/cgi-bin/"
ScriptAlias /directory/ "/usr/local/apache/secret-cgi-bin/"
ScriptAlias /area_one/cgi-bin/ "/usr/local/apache/cgi-bin/"
ScriptAlias /area_two/cgi-bin/ "/usr/local/apache/cgi-bin/"
ScriptAlias /area_three/cgi-bin/ "/usr/local/apache/cgi-bin/"
Alias /cgi-bin/ "/usr/local/apache/cgi-bin/"
<Directory /usr/local/apache/cgi-bin>
AllowOverride None
Options +ExecCGI
SetHandler cgi-script
</Directory>
<Files "/home/web/alpha-complex/welcome">
AllowOverride None
Options +ExecCGI
SetHandler cgi-script
</Files>
<FilesMatch "/home/web/alpha-complex/cgi-bin/*.cgi>
AllowOverride None
Options ExecCGI
SetHandler cgi-script
</FilesMatch>
<Directory "/usr/local/apache/cgi-bin">
AllowOverride None
Options +ExecCGI
SetHandler cgi-script
Order allow,deny
Allow from all
</Directory>
<Directory "/usr/local/apache/cgi-bin">
AllowOverride None
Options ExecCGI
AddHandler cgi-script .cgi
<IfModule mod_fastcgi.c>
AddHandler fastcgi-script .fcgi
</IfModule>
Order allow,deny
Allow from all
</Directory>
<Location /protected>
AuthName Pod Bay Doors
AuthType Basic
AuthUserFile /home/alpha-complex/auth/podbayaccess.auth
require user anna betty clara
</Location>
<Location /protected>
AuthName Pod Bay Doors
AuthType Basic
FastCgiAuthenticator cgi-bin/authenticate.fcgi
require user anna betty clara
</Location>
<Location /protected>
AuthName Top Secret
AuthType Basic
FastCgiAccessChecker cgi-bin/accesscheck.fcgi
FastCgiAuthenticator cgi-bin/authenticate.fcgi
FastCgiAuthorizer cgi-bin/authorizer.fcgi
</Location>
--------------------------------------------------------------------------------
LogFormat "%V: %h %l %u %t \"%r\" %>s %b"
LogFormat "%A: %h %l %u %t \"%r\" %>s %b"
--------------------------------------------------------------------------------
Proxy
ProxyRequests on
ProxyRequests off
--------------------------------------------------------------------------------
Configuring Apache As a Proxy
Listen 80
Listen 8080
User httpd
Group httpd
# dynamic servers load modules here...
ServerName www.alpha-complex.com:80
ServerAdmin webmaster@alpha-complex.com
DocumentRoot /home/www/alpha-complex
ErrorLog logs/main_error
TransferLog logs/main_log
<VirtualHost 204.148.170.3:8080>
ServerName proxy.alpha-complex.com
ProxyRequests On
ErrorLog logs/proxy_error
TransferLog logs/proxy_log
</VirtualHost>
<VirtualHost 204.148.170.3:8080>
ServerName proxy.alpha-complex.com
ErrorLog logs/proxy_error
TransferLog logs/proxy_log
ProxyRequests on
CacheRoot /usr/local/apache/cache
# limit use of this proxy to hosts on the local network
<Proxy *>
order deny,allow
deny from all
allow from 204.148.170
</Proxy>
</VirtualHost>
--------------------------------------------------------------------------------
<Directory proxy:*>
... directives for proxy requests only ...
</Directory>
<Proxy *>
... directives for proxy requests only ...
</Proxy>
<Proxy http:*>
... proxy directives for http ...
</Proxy>
<Proxy ftp:*>
... proxy directives for ftp ...
</Proxy>
<Proxy */www.alpha-complex.com/*>
... proxy directives for www.alpha-complex.com ...
</Proxy>
<ProxyMatch www\.alphacomplex\.com>
... proxy directives for www.alpha-complex.com ...
</ProxyMatch>
<ProxyMatch \.html$>
... proxy directives for www.alpha-complex.com ...
</ProxyMatch>
--------------------------------------------------------------------------------
Blocking Sites via the Proxy
ProxyBlock www.badsite.com baddomain.dom badword
--------------------------------------------------------------------------------
Forwarding Proxied URLs
ProxyPass /users/ http://users.alpha-complex.com/
ProxyPass /secure/ http://secure.alpha-complex.com/secure-part/
ProxyPass / http://realwww.intranet.alpha-complex.com
ProxyPassReverse / http://realwww.intranet.alpha-complex.com
<Location /users/>
RequestHeader set X-Proxy-Request yes
ProxyPass http://users.alpha-complex.com/
</Location>
<Location /secure/>
ProxyPass https://externalserver.elsewhere-on-the-internet.com/
</Location>
<Location /secure/>
SSLRequireSSL
ProxyPass http://internal-server.alpha-complex.com/
</Location>
<LocationMatch "\.jsp$">
ProxyPass tomcat.alpha-complex.com
ProxyPassReverse tomcat.alpha-complex.com
</LocationMatch>
--------------------------------------------------------------------------------
Relaying Requests to Remote Proxies
ProxyRemote http http://www.proxyremote.com
ProxyRemote http://www.mainsite.com http://mirror.mainsite.com:8080
ProxyRemote ftp ftp://ftp.ftpmirror.com
ProxyRemote * http://proxy.remote.com
--------------------------------------------------------------------------------
ProxyTimeout 60
--------------------------------------------------------------------------------
Cache
CacheEnable mem /small_images/
CacheEnable fd /large_but_static_documents/
CacheEnable disk /
CacheDisable /dont_cache_this/
CacheRoot /usr/local/apache/proxy/
CacheDirLevels 6
CacheSize 102400
CacheMinFileSize 1024
CacheMaxFileSize 1048576
# trim the cache every 75 minutes
CacheGcInterval 1.25
# trim the cache every 12 minutes
CacheGcInterval 0.2
NoCache *
CacheDisable interactive.alpha-complex.com
CacheDisable uncacheddomain.net
CacheDisable badword
--------------------------------------------------------------------------------
Setting the Memory Cache Size
MCacheSize 10240
MCacheMaxObjectSize 102400
MCacheMinObjectSize 512
--------------------------------------------------------------------------------
# Apache Server Configuration for Clustering Proxy
#
### Basic Server Setup
# The proxy takes the identity of the web site...
ServerName www.alpha-complex.com
# Basic configuration.
# Note that the DocumentRoot is a 'safe' irrelevant value as we don't serve
# anything directly
ServerAdmin webmaster@alpha-complex.com
ServerRoot /usr/local/apache
DocumentRoot /usr/local/apache/proxysite
ErrorLog /usr/local/apache/proxy_error
TransferLog /usr/local/apache/proxy_log
# Choose a non-privileged user and group
User httpd
Group httpd
# Dynamic servers load their modules here...
# Note that if this proxy is only a proxy, we don't need most standard
# modules loaded.
# Don't waste time on things we don't need
HostnameLookups off
# This server is only for proxying so switch off everything else
<Directory />
Options None
AllowOverride None
</Directory>
# Allow a local client to access the server status
<Location />
order allow,deny
deny from all
allow from 127.0.0.1
SetHandler server-status
</Location>
### Part 1 - Rewrite
# switch on URL rewriting
RewriteEngine on
# Define a log for debugging but set the log level to zero to disable it for
# performance
RewriteLog logs/proxy_rewrite
RewriteLogLevel 0
# define the cluster servers map
RewriteMap cluster rnd:/usr/local/apache/rewritemaps/cluster.txt
# rewrite the URL if it matches the web server host
RewriteRule ^http://www\.(.*)$ http://{cluster:www}.$2 [P,L]
# forbid any URL that doesn't match
RewriteRule .* - [F]
### Part 2 - Proxy
ProxyPassReverse / http://www1.alpha-complex.com/
ProxyPassReverse / http://www2.alpha-complex.com/
ProxyPassReverse / http://www3.alpha-complex.com/
ProxyPassReverse / http://www4.alpha-complex.com/
ProxyPassReverse / http://www5.alpha-complex.com/
ProxyPassReverse / http://www6.alpha-complex.com/
# We don't want caching, preferring to let the back end servers take the
# load, but if we did:
#
# Apache 2 only:
CacheOn on
CacheEnable disk /
# Apache 2 and 1.3:
#CacheRoot /usr/local/apache/proxy
#CacheSize 102400
--------------------------------------------------------------------------------
Enabling the Server Status Page
<Location /server/status>
SetHandler server-status
</Location>
<Location /info>
ExtendedStatus on
AddHandler server-status .status
</Location>
--------------------------------------------------------------------------------
Server Info
<Location /server-info>
SetHandler server-info
</Location>
<Location /info>
AddHandler server-status .status
AddHandler server-info .info
</Location>
<Location /server-status>
SetHandler server-status
order deny,allow
deny from all
allow from 127.0.0.1 192.168.1.100
</Location>
<VirtualHost 192.168.2.1:81>
Options None
AllowOveride None
# locations
DocumentRoot /usr/local/apache/status/html
ErrorLog /usr/local/apache/status/logs/error_log
TransferLog /usr/local/apache/status/logs/access_log
# SSI directives
SSLEnable
# Authentication
AuthType Basic
AuthName Status Host
AuthUserFile /usr/local/apache/status/auth/password.file
require valid-user
# host access
order deny,allow
deny from all
allow from 192.168.2.100
# handlers
AddHandler server-status -status
AddHandler server-info -info
# additional info
AddModuleInfo mod_fastcgi "<a href=/docs/mod_fastcgi>Notes</a>"
</VirtualHost>
--------------------------------------------------------------------------------
Auth
<Location /secure>
AuthName <name_of_realm>
AuthType Basic|Digest
Auth<???>UserFile <path_to_users_file_or_db>
Auth<???>GroupFile <path_to_groups_file_or_db>
require valid-user | user <list of users> | group <list of groups>
Auth<???>Authoritative on|off
</Location>
<Location /file_auth>
AuthName "File Authentication"
AuthType Basic
AuthUserFile /usr/local/apache/auth/password.file
AuthGroupFile /usr/local/apache/auth/groups.file
require user user1 user2 group group1 group2
AuthAuthoritative on
</Location>
<Location /dbm_auth>
AuthName "DBM Authentication"
AuthType Basic
AuthDBMUserFile /usr/local/apache/auth/password.dbm
AuthDBMGroupFile /usr/local/apache/auth/groups.dbm
require user user1 user2 group group1 group2
AuthDBMAuthoritative on
</Location>
<Location /anonymous>
AuthName "Guest Access"
AuthType Basic
Anonymous guest visitor cypherpunk
require valid-user
Anonymous_Authoritative on
Anonymous_MustGiveEmail on
Anonymous_VerifyEmail on
Anonymous_LogEmail on
Anonymous_NoUserID off
</Location>
<Location /digestives>
AuthName "Digestion Section"
AuthType Digest
AuthDigestDomain /digestives
AuthDigestFile /usr/local/apache/auth/passwords.md5
AuthDigestGroupFile /usr/local/apache/auth/groups.file
require valid-user
</Location>
--------------------------------------------------------------------------------
LDAP AUTH
<Location /ldapsecure>
AuthName "LDAP Security Barrier"
AuthType Basic
AuthLDAPUrl http://ldap.alphacomplex.com:4444/o=AlphaComplex
AuthLDAPGroupAttribute sector
require valid-user
AuthLDAPAuthoritative on
</Location>
--------------------------------------------------------------------------------
<Location /combined_auth>
AuthName "Combined Authentication"
AuthType Basic
AuthDBMUserFile /usr/local/apache/auth/password.dbm
AuthDBMAuthoritative off
AuthUserFile /usr/local/apache/auth/password.file
</Location>
<Location />
AuthName "Who Are You and Where Do You Come From?"
AuthType Basic
AuthUserFile /usr/local/apache/auth/password.file
require valid-user
order deny,allow
deny from all
allow from www.trustedally.com
Satisfy all
</Location>
--------------------------------------------------------------------------------
Securing Basic Authentication with SSL
<Location /private>
AuthName "Authorized Personnel Only"
AuthType Basic
AuthUserFile auth/personnel.auth
require valid-user
SSLEnable on
SSLRequireSSL
</Location>
--------------------------------------------------------------------------------
Basic SSL Configuration
Listen 80
Listen 443
# Switch on the SSL engine--(for Apache 1.3 Apache-SSL
# use SSLEnable instead)
SSLEngine on
# Specify the server's private key
SSLCertificateKeyFile conf/ssl/www.alpha-complex.com.key
# Specify the certificate for the private key
SSLCertificateFile conf/ssl/www.alpha-complex.com.crt
<VirtualHost 192.168.1.1:443>
ServerName www.alpha-complex.com
DocumentRoot /home/www/alpha-complex
... virtual host directives ...
SSLEngine on
SSLCertificateFile conf/ssl/www.alpha-complex.com.crt
SSLCertificateKeyFile conf/ssl/www.alpha-complex.com.key
</VirtualHost>
<VirtualHost 192.168.1.1:*>
ServerName www.alpha-complex.com
DocumentRoot /home/www/alpha-complex
... virtual host directives ...
</VirtualHost>
<Directory /home/www/alpha-complex/secure/>
SSLrequireSSL
</Directory>
<Location /secure-area/>
SSLRequireSSL
</Location>
<Location /secure-area/non-ssl-browsers/>
order deny,allow
allow from all
Satisfy any
</Location>
<Directory /home/www/alpha-complex/secure/>
SSLRequireSSL
order deny,allow
deny from all
allow from 192.168 www.trusted.com
Satisfy any
</Directory>
--------------------------------------------------------------------------------
SSL and Logging
SSLLog /home/sites/alpha-complex/logs/ssl_log
SSLLog logs/ssl_log
SSLLogLevel warn
SSLLogLevel none
LogFormat "%h %l %u %t \"%r\" %>s %b %{SSL_SESSION_ID}x"
CustomLog logs/ssl_log "%h %t \"%r\" %{SSL_PROTOCL}x %{SSL_SESSION_ID}x %{SSL_CIPHER}%{SSL_USEKEYSIZE}x:%{SSL_ALGKEYSIZE}x" env=HTTPS
--------------------------------------------------------------------------------
SSL and Virtual Hosts
User httpd
Group httpd
# Ports
Listen 80
Listen 443
# main server configuration
ServerName www.alpha-complex.com
ServerAdmin webmaster@alpha-complex.com
DocumentRoot /home/www/alpha-complex
TransferLog logs/access_log
ErrorLog logs/error_log
SSLCertificateFile conf/ssl/www.alpha-complex.com.crt
SSLCertificateKeyFile conf/ssl/www.alpha-complex.com.key
# main server, port 443 (HTTPS)
<VirtualHost 192.168.1.1:443>
SSLEngine on
# server configuration inherited from main server
</VirtualHost>
# main server, port 80 (HTTP)
<VirtualHost 192.168.1.1:80>
# server configuration inherited from main server
</VirtualHost>
# another server, HTTP only, any port
<VirtualHost 192.168.1.2>
... virtual host directives ...
</VirtualHost>
# yet another server, HTTPS only, any port
<VirtualHost 192.168.1.3>
SSLEngine on
... virtual host directives ...
</VirtualHost>
--------------------------------------------------------------------------------
User httpd
Group httpd
# Ports
Listen 80
Listen 443
# main server configuration
ServerName www.alpha-complex.com
ServerAdmin webmaster@alpha-complex.com
DocumentRoot /home/www/alpha-complex
TransferLog logs/access_log
ErrorLog logs/error_log
# uncomment these and remove the first set below for inheritance
#SSLCertificateFile conf/ssl/www.alpha-complex.com.crt
#SSLCertificateKeyFile conf/ssl/www.alpha-complex.com.key
# main server, port 443 (HTTPS)
<VirtualHost 192.168.1.1:443>
SSLEngine on
SSLCertificateFile conf/ssl/www.alpha-complex.com.crt
SSLCertificateKeyFile conf/ssl/www.alpha-complex.com.key
# Server configuration inherited from main server
</VirtualHost>
# another server, HTTPS only, any port
<VirtualHost 192.168.1.3>
SSLEngine on
SSLCertificateFile conf/ssl/www.another.com.crt
SSLCertificateKeyFile conf/ssl/www.another.com.key
... virtual host directives ...
</VirtualHost>
--------------------------------------------------------------------------------
Directive Default Value Alternative Example Location
ServerRoot /usr/local/apache /etc/httpd
ErrorLog <ServerRoot>/logs/error_log /etc/httpd/logs/errors
DocumentRoot <ServerRoot>/htdocs /home/httpd/public_html
--------------------------------------------------------------------------------
User nobody (Unix Only)
Group nobody (Unix Only)
ServerType standalone
ServerRoot /usr/local/apache (Where Apache folder? The server root is where Apache keeps all its essential files.)
ServerName www.alpha-complex.com (Site URL)
ServerAdmin administrator@email.com (Admin Email)
Listen 80 (Listen only coonections on this IP and Port)
Listen 443
Listen 127.0.0.1:80
Listen 127.0.0.1:443
Listen 192.168.1.1:80
Listen 192.168.1.1:443
ErrorLog /usr/local/apache/logs/error_log (Default Error Log)
TransferLog /logs/access_log (Also known as Access Log)
DocumentRoot htdocs (Where all site files? Default folder for all site files.)
DocumentRoot /usr/local/apache/htdocs
--------------------------------------------------------------------------------
Base Master Configuration File
httpd.conf:
ServerName www.alpha-complex.com
Listen 192.168.1.1:80
Listen 192.168.1.1:443
User nobody
Group nobody
ServerAdmin webmaster@alpha-complex.com
#ServerRoot /usr/local/apache
#ErrorLog logs/error_log
TransferLog logs/access_log
DocumentRoot /home/www/alpha-complex
--------------------------------------------------------------------------------
# Load Apache modules
LoadModule vhost_alias_module libexec/mod_vhost_alias.so
...
LoadModule setenvif_module libexec/mod_setenvif.so
--------------------------------------------------------------------------------
# Virtual host directives
<VirtualHost 192.168.1.1>
Include conf/virtualhost.conf
Include conf/intranet_one.conf
Include /etc/httpd/conf/*.conf
Include /etc/httpd/conf/networks/*.conf
Include /etc/httpd/conf/[0-9][0-9]_*.conf
</VirtualHost>
<VirtualHost 192.168.10.1>
Include conf/virtualhost.conf
Include conf/intranet_ten.conf
</VirtualHost>
<VirtualHost 204.148.170.4>
Include conf/virtualhost.conf
Include conf/extranet.conf
</VirtualHost>
<VirtualHost www.beta-complex.com>
User beta
Group betausers
...
</VirtualHost>
<VirtualHost 204.148.170.3>
ServerName www.alpha-complex.com
ServerAlias alpha-complex.com *.alpha-complex.com
ServerAdmin webmaster@alpha-complex.com
DocumentRoot /home/www/alpha-complex
ErrorLog logs/alpha-complex_errors
TransferLog logs/alpha-complex_log
</VirtualHost>
<VirtualHost 204.148.170.3:80>
# virtual host directives
...
<Location />
RemoveHandler .shtml
<Location>
</VirtualHost>
# SSL configuration directives
SSLEngine off
<VirtualHost 204.148.170.7:443>
# virtual host directives
...
SSLEngine on
</VirtualHost>
Listen 443
Listen 80
# server level directives
...
<VirtualHost 204.148.170.3:*>
ServerName www.alpha-complex.com
AssignUserID alphabadm alphagroup
# virtual host directives
...
</VirtualHost>
<VirtualHost 204.148.170.4:80>
ServerName www.beta-complex.com:80
AssignUserID betavadm betagroup
# virtual host directives
...
</VirtualHost>
<VirtualHost 204.148.170.5:443>
ServerName secure.troubleshooter.com:443
AssignUserID primeuadm alphagroup
SSLEngine on
# virtual host directives
...
</VirtualHost>
<VirtualHost 204.148.170.5>
ServerName users.alpha-complex.com
# virtual host directives
...
</VirtualHost>
<VirtualHost 204.148.170.5>
ServerName secure.alpha-complex.com
# virtual host directives
...
</VirtualHost>
<VirtualHost 204.148.170.5>
ServerName www.alpha-complex.com
# virtual host directives
...
</VirtualHost>
<VirtualHost 204.148.170.3>
ServerName www.alpha-complex.com
ServerAlias www.alpha-prime.com *complex*.???
ServerAdmin ...
DocumentRoot ...
ErrorLog ...
TransferLog ...
</VirtualHost>
<VirtualHost 204.148.170.3:*>
ServerName www.alpha-complex.com:80
ServerAlias *
RewriteEngine On
RewriteRule .* - [R]
</VirtualHost>
<VirtualHost 204.148.170.5 204.148.170.7:443>
# this name resolves to 204.148.170.7
ServerName secure.alpha-complex.com:443
# this alias matches hosts on the name-based IP
ServerAlias secure.*
ServerAdmin secure@alpha-complex.com
DocumentRoot /home/www/alpha-complex/
ErrorLog logs/alpha-complex_sec_error
TransferLog logs/alpha-complex_sec_log
# this assumes we've specified the other SSL directives elsewhere
<Location /secure/>
SSLEngine on
</Location>
</VirtualHost>
<VirtualHost 204.148.170.3>
ServerName server1.alpha-complex.com
ServerAdmin webmaster@alpha-complex.com
ServerAlias server[0-9].alpha-complex.com
VirtualDocumentRoot /home/www/%1.1+.alpha-complex/web/
VirtualScriptAlias /home/www/%1.1+.alpha-complex/cgi-bin/
ErrorLog logs/alpha-complex_error
TransferLog logs/alpha-complex_log
</VirtualHost>
--------------------------------------------------------------------------------
# Local Apache customizations.
# set additional/conditional environment variables.
Include /etc/httpd/conf/Env.conf
# IP, Host, and URL based access restrictions.
Include /etc/httpd/conf/Access.conf
# mod_perl configuration.
Include /etc/httpd/conf/Perl.conf
# All-sites directory configuration.
Include /etc/httpd/conf/Sites.conf
# Virtual hosts
Include /etc/httpd/conf/Vhost.conf
--------------------------------------------------------------------------------
AccessFileName .access .config .perdirectory (The AccessFileName directive causes Apache to look for files called .access, .config,
and .perdirectory and parse them in the order specified)
--------------------------------------------------------------------------------
Container Directives
# <VirtualHost> (<VirtualHost> allows additional hosts and Web sites to be defined alongside the main server host site. Each virtual host can have its
own name, IP address, and error and access logs.)
<VirtualHost 192.168.1.2>
ServerName www.beta-complex.com
ServerAdmin troubleshooter@beta-complex.com
CustomLog /logs/beta_access_log common
TransferLog /logs/beta_access_log
ErrorLog /logs/beta_error_log
DocumentRoot /home/www/beta-complex
</VirtualHost>
# <Directory> (For all files in this directory)
<Directory />
AuthType Basic
AuthUserFile /usr/local/apache/auth/password.file
</Directory>
<Directory />
Options none
AllowOverride none
order allow,deny
deny from all
</Directory>
<Directory /home/www/alpha-complex>
Options Includes FollowSymLinks
AllowOverride FileInfo
allow from all
</Directory>
<Directory /home/www/*>
AllowOverride All
</Directory>
# <DirectoryMatch> (<DirectoryMatch> is for specifying regular expressions instead of wildcards in the directory specification)
<DirectoryMatch "/[A-Z][0-9]{2}/">
AllowOverride All
</DirectoryMatch>
# <Files>(<Files> are similar to <Directory> but match files instead.)
<Directory /home/www/alpha-complex/gallery>
<Files *.gif>
SetHandler /cgi-bin/burn-gifs.cgi
</Files>
</Directory>
# <FilesMatch> (<FilesMatch> is for specifying regular expressions instead of wildcards in the file’s specification.)
<Directory /home/www/alpha-complex/wanted/mugshots>
<FilesMatch "\.(gif|jpg)$">
SetHandler /cgi-bin/process-image.cgi
</Files>
</Directory>
# <Location> (<Location> operates in a similar manner to <Directory> but applies to a URL rather than a physical file location.)
<Location /server-info>
SetHandler server-info
</Location>
<Location /secure/administrators>
AuthName "Administrator's Area"
require user administrator
</Location>
<Location /secure/members>
AuthName "Members Only"
require valid-user
</Location>
# <LocationMatch> (<LocationMatch> is for specifying regular expressions instead of wildcards in the location specification.)
<LocationMatch "^/[A-Z][a-z]+/$">
SetHandler server-info
</LocationMatch>
<Location /secure-area>
order deny, allow
deny from all
allow from 192.168.1.100
allow from 192.168.1.101
</Location>
<Location /secure-area>
order deny, allow
deny from all
allow from 192.168.1.100
allow from 192.168.1.101
Satisfy all
AuthName "Secure Area"
AuthType Basic
AuthUserFile /usr/local/apache/auth/password.file
require valid-user
</Location>
--------------------------------------------------------------------------------
Alias /doc /usr/doc
Alias /icons/ /usr/local/apache/icons/
Alias /icons/ /usr/local/images/alternative-icons/
--------------------------------------------------------------------------------
• Options: The Options directive controls how Apache regards the file system. It
takes one or more options as parameters, each of which modifies how the server
behaves on encountering a particular situation such as an executable file, a
symbolic link, or a directory that contains no default index page.
• AllowOverride: The AllowOverride directive controls which directives can be
placed in per-directory .htaccess files to override the server configuration,
including the Options directive.
--------------------------------------------------------------------------------
Options All None ExecCGI FollowSymLinks SymLinksIfOwnerMatch Includes IncludesNOEXEC Indexes MultiViews
Options Indexes Includes
Options FollowSymLinks
<Location />
Options -Indexes
</Location>
<Location /ftp/>
Options +Indexes
</Location>
All - Enables all options except for MultiViews.
ExecCGI - Permits execution of CGI scripts.
FollowSymLinks - Files or directories referred to via symbolic links will be followed. Has no effect inside <Location> containers.
SymLinksIfOwnerMatch - The server will only follow symbolic links for which the target file or directory is owned by the same user ID as the link.
Includes - Permits Server-Side Includes (SSIs).
IncludesNOEXEC - Permits Server-Side Includes but limits execution of CGI scripts.
Indexes - If a URL that maps to a directory is requested, and there’s no corresponding index file identified with the DirectoryIndex directive, Apache will create and return a formatted listing of the directory contents, controlled by the IndexOptions directive,
MultiViews - Content-negotiated MultiViews are allowed. This option isn’t enabled by the use of All.
None - Disables all options.
--------------------------------------------------------------------------------
Options Modifiers
Position Modifier
Grandparent Options Indexes Includes FollowSymLinks
Parent Options +ExecCGI –Indexes
Directory Options -Includes +IncludesNoExec
Result Options FollowSymLinks ExecCGI IncludesNoExec
--------------------------------------------------------------------------------
AllowOverride All None FileInfo Limit AuthConfig
<Directory />
AllowOverride None
</Directory>
<Location />
AllowOverride All
</Location>
--------------------------------------------------------------------------------
• order deny,allow: Implements a restrictive access policy where most hosts are
denied and then a smaller subset given access
• order allow,deny: Implements a permissive access policy where most hosts are
allowed and then a smaller subset refused access
allow from crawler.beta-complex.com
deny from .beta-complex.com
# traditional partial IP address
allow 192.168
# network address and netmask
allow 192.168.0.0/255.255.0.0
# network address and bitmask
allow 192.168.0.0/16
<Directory />
order deny,allow
deny from all
allow from localhost
</Directory>
<Directory />
order allow,deny
allow from all
deny from robot.trouble.com
</Directory>
<Directory />
order deny,allow
deny from .trouble.com
allow from no.trouble.com little.trouble.com
</Directory>
<Directory /internal-eyes-only/>
order deny,allow
deny from all
allow from 127.0.0.1 192.168.1 192.168.2
</Directory>
<Directory /my-ipv6-eyes-only/>
order deny,allow
deny from all
allow from fe80::910:a4ff:aefe:9a8, 127.0.0.1
</Directory>
<Directory /no-indexing-here/>
order allow,deny
allow from all
# 101.202.85.5 is the IP for robot.trouble.com...
deny from robot.trouble.com 101.202.68.5
</Directory>
BrowserMatch ^Mozilla lizards_rule
<Directory /mozilla-area/>
order deny,allow
deny from all
allow from env=lizards_rule
</Directory>
SetEnvIf Request_Protocol ^HTTP/1.1 http_11_ok
<Directory /http11only/>
order deny,allow
deny from all
allow from env=http_11_ok
</Directory>
SetEnvIf Referer ^http://www.alpha-prime.com/secure/links_page.html origin_ok
<Directory /alphaprime_users_only/>
order deny,allow
deny from all
allow from env=origin_ok
</Directory>
<Location /registered-users-only/>
# allow only registered users access
AuthName "Registered Users Only"
AuthType Basic
AuthDBMUserFile /usr/local/apache/auth/password.dbm
require valid-user
# lock out external clients
order deny,allow
deny from all
allow from 192.168.1 192.168.2
# allow either access method
Satisfy any # or Satisfy all
</Location>
--------------------------------------------------------------------------------
<Directory /ftp/>
Options +Indexes
IndexOrderDefault Ascending Name
# IndexOrderDefault Ascending Size
# IndexOrderDefault Descending Date
IndexIgnore .??* *~ *# *.bak HEADER* README* SCCS RCS
DirectoryIndex index.html
DirectoryIndex index.html index.htm index.shtml home.html home.htm index.cgi
</Directory>
--------------------------------------------------------------------------------
BrowserMatch Mozilla lizard=true
SetEnvIf User-Agent Mozilla lizard=true
BrowserMatch .*spider.* is_a_robot robot=spider !give_access
# test for HTTP/1.0 and HTTP/1.1 requests
SetEnvIf Request_Protocol ^HTTP/1.1 http_proto=11
SetEnvIf Request_Protocol ^HTTP/1.0 http_proto=10
# test for environment variable 'http_proto' - if unset assume HTTP/0.9
SetEnvIf http_proto !^1 http_proto=09
BrowserMatchNoCase crawler robot
BrowserMatchNoCase yahoo robot=yahoo
BrowserMatchNoCase infoseek robot=infoseek
BrowserMatchNoCase spider robot
BrowserMatchNoCase spyder robot
BrowserMatchNoCase bot robot
BrowserMatchNoCase harvest robot=harvest
BrowserMatchNoCase crawler robot=crawler
BrowserMatchNoCase yahoo robot=yahoo
--------------------------------------------------------------------------------
RewriteCond %{HTTP_USER_AGENT} .*robot.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} .*crawler.* [NC,OR]
RewriteCond %{REMOTE_HOST} badrobot.com$ [NC]
RewriteRule ^/not-indexable/ - [F]
--------------------------------------------------------------------------------
TypesConfig conf/mime.types
Content-Type: image/gif
text/html html htm
text/plain asc txt
text/sgml sgml sgm
image/jpeg jpeg jpg jpe
image/gif gif
image/png png
application/x-javascript js
application/pdf pdf
application/postscript ai eps ps
audio/mpeg mpga mp2 mp3
video/quicktime qt mov
AddType application/x-mylanguage .myl .mylanguage
AddType text/mylanguage myl mylanguage
AddType text/svg+xml .svg
DefaultType text/html
--------------------------------------------------------------------------------
AddEncoding x-gzip .gz
AddEncoding x-compress .Z
AddEncoding zip .zip
AddEncoding mac-binhex40 .hqx
AddEncoding zip zip
Content-Type: text/html
Content-Encoding: zip
<Directory /home/sites/alpha-complex/encoded>
AddEncoding x-gzip gz
<Files *.gz.html>
RemoveEncoding gz
</Files>
<FilesMatch \.gz$>
AddEncoding x-gzip gz
</FilesMatch>
</Directory>
<Directory /mixed/html/and/images>
SetOutputFilter Deflate
<FilesMatch \.(gif|jpg|png)$>
SetEnv no-gzip
</Files>
</Directory>
<Directory /mixed/html/and/images>
SetOutputFilter Deflate
<FilesMatch \.(gif|jpg|png)$>
SetEnv no-gzip all-browsers
</Files>
BrowserMatch ^Mozilla/4 no-gzip
BrowserMatch " MSIE" !no-gzip
Header append Vary User-Agent env=!all-browsers
</Directory>
--------------------------------------------------------------------------------
Content-Language: en
DefaultLanguage en
AddLanguage en .en .english
AddLanguage de .de .deutsch .german
LanguagePriority en de fr
<Directory /deutsch/>
DefaultLanguage de
</Directory>
<Directory /deutsch/>
<Files *.html>
DefaultLanguage de
</Files>
</Directory>
--------------------------------------------------------------------------------
Content-type: text/html; charset=ISO-8859-1
AddCharSet ISO-8859-7 .gr .greek .latin7
AddDefaultCharset ISO-8859-7
AddType text/html;charset=ISO-8859-7 .grhtml
AddDefaultCharset on
<Location /images>
# our images don't contain text so we don't want or need a charset
AddDefaultCharset off
</Location>
<Location /images/buttons/greek>
AddDefaultCharset ISO-8859-7
</Location>
--------------------------------------------------------------------------------
RewriteEngine on
<Location /type-mapped-files>
AddHandler type-map .var
RewriteRule ^(.*\.html)$ $1.var [NS]
</Location>
AliasMatch ^/(type-mapped-files/.*\.html)$ /home/sites/alpha-compex/$1.var
<Location /type-mapped-files>
AddHandler type-map .var
</Location>
--------------------------------------------------------------------------------
Alias
Alias /images/ /home/gallery/photos/
AliasMatch /images/(.*)\.gif$ /usr/local/apache/images/$1.gif
AliasMatch /(.*)/images/(.*)\.gif$ /usr/local/apache/images/$1/$2.gif
AliasMatch ^(.*).logo$ /cgi-bin/logo-parser?$1.logo
ScriptAlias /cgi-bin/ /usr/local/apache/cgibin/
ScriptAliasMatch ^/cgi-bin/(.*)\.cgi$ /usr/local/apache/cgibin/$1.cgi
--------------------------------------------------------------------------------
Basic Redirection
Redirect permanent /archive http://archive.alpha-prime.com/archive/alpha-complex
Redirect permanent /archive http://archive.alpha-prime.com/archive/alpha-complex?querystring=new
permanent 301 - The requested resource has been assigned a new permanent URI, and any future references to this resource should use the returned URL.
temp 302 - The requested resource resides temporarily under a different URI.
seeother 303 - The response to the request can be found under a different URL and should be retrieved using a GET method, irrespective of the HTTP method used for the original request.
gone 410 - The requested resource is no longer available.
Use Proxy 305 - The requested resource must be retrieved through the proxy server given by the URL. The client then reissues the request to the proxy.
Temporary Redirect 307 - Many clients interpret a 302 response as if it were a 303 response and change the request method to GET, in violation of the HTTP/1.1 specification. To avoid this, 307 can be used to inform the client unambiguously that the new URL should be requested with the same HTTP method as the original.
--------------------------------------------------------------------------------
Redirection with Regular Expressions
RedirectMatch (.*)\.(gif|jpg)$ http://images.alpha-complex.com/imagecache/$1.$2
RedirectMatch 305 \.(gif|jpg)$ http://proxy.alpha-prime.com
--------------------------------------------------------------------------------
LoadModul rewrite_module modules/mod_rewrite.so
RewriteEngine on
RewriteRule /images/(.*)\.gif$ /usr/local/apache/images/$1.gif
RewriteRule /abcde/(.*) /12345/$1
RewriteRule /12345/(.*) /fghijk/$1
RewriteRule /abcde/(.*) /fghijk/\$1=$1
RewriteRule ^(.*)$ http://alpha-complex.com/$1
# define our list of trusted hosts
RewriteCond %{REMOTE_ADDR} ^192\.168\..* [OR]
RewriteCond %{REMOTE_ADDR} ^127\.0\.0\.1 [OR]
RewriteCond %{REMOTE_HOST} ^trusted.comrade.com$
# if the above conditions hold, don't touch the URL at all and skip the next rule
RewriteRule .* - [S=1]
# otherwise, redirect the client to the homepage
RewriteRule .* /index.html [R]
# we could rewrite the URL from the trusted hosts further here...
# a server-level rewrite rule
RewriteRule /abcde/(.*) /12345/$1
<Directory /container>
RewriteRule /12345/(.*) /fghijk/$1
# the server-level rewrite rule is not inherited here
</Directory>
<Directory /inherited/here>
# server-level Rewrite rule applies here
RewriteOptions inherit
</Directory>
<Directory /container/inherited/here>
# both RewriteRule directives apply here
RewriteOptions inherit
</Directory>
--------------------------------------------------------------------------------
RewriteCondVariables
Functionality Variable Name
Server internals DOCUMENT_ROOT, SERVER_ADMIN, SERVER_NAME, SERVER_ADDR, SERVER_PORT, SERVER_PROTOCOL, SERVER_SOFTWARE HTTP request REMOTE_ADDR, REMOTE_HOST, REMOTE_USER, REMOTE_IDENT, REQUEST_METHOD, SCRIPT_FILENAME, PATH_INFO, QUERY_STRING, AUTH_TYPE
HTTP headers HTTP_USER_AGENT, HTTP_REFERER, HTTP_COOKIE, HTTP_FORWARDED, HTTP_HOST, HTTP_PROXY_CONNECTION, HTTP_ACCEPT
Time TIME_YEAR, TIME_MON, TIME_DAY, TIME_HOUR, TIME_MIN, TIME_SEC, TIME_WDAY, TIME
Specials API_VERSION, THE_REQUEST, REQUEST_URI, REQUEST_FILENAME, IS_SUBREQ
--------------------------------------------------------------------------------
SSI Server Side Includes
Enable SSI
Options +Includes
# allow static content to be included, but do not run CGIs
Options +IncludesNOEXEC
<Location /ssidocs>
Options +Includes
</Location>
<Location />
AddHandler server-parsed .shtml
</Location>
<Location /include>
SetHandler server-parsed
</Location>
AddHandler server-parsed .shtml .html .htm
<Location /ssi-cgibin>
Options +ExecCGI +Includes
AllowOverride None
AddHandler cgi-script .cgi
AddOutputFilter Includes .cgi
</Location>
Format of SSI Commands
<!--#command parameter="value" parameter="value" ... -->
<!--#include virtual="/include/$1" -->
<!--#set var="CLEARED_TITLE" value="Welcome, Troubleshooter" -->
<!--#set var="UNCLEARED_TITLE" value="You are not cleared to read this document" -->
<!--#if expr="${CLEARED}" -->
<!--#set var="TITLE” value="CLEARED_TITLE" -->
<!--#else -->
<!--#set var="TITLE" value="UNCLEARED_TITLE" -->
<!--#endif -->
<!--#echo var="$TITLE" -->
--------------------------------------------------------------------------------
CGI
ScriptAlias /cgi-bin/ "/usr/local/apache/cgi-bin/"
ScriptAlias /directory/ "/usr/local/apache/secret-cgi-bin/"
ScriptAlias /area_one/cgi-bin/ "/usr/local/apache/cgi-bin/"
ScriptAlias /area_two/cgi-bin/ "/usr/local/apache/cgi-bin/"
ScriptAlias /area_three/cgi-bin/ "/usr/local/apache/cgi-bin/"
Alias /cgi-bin/ "/usr/local/apache/cgi-bin/"
<Directory /usr/local/apache/cgi-bin>
AllowOverride None
Options +ExecCGI
SetHandler cgi-script
</Directory>
<Files "/home/web/alpha-complex/welcome">
AllowOverride None
Options +ExecCGI
SetHandler cgi-script
</Files>
<FilesMatch "/home/web/alpha-complex/cgi-bin/*.cgi>
AllowOverride None
Options ExecCGI
SetHandler cgi-script
</FilesMatch>
<Directory "/usr/local/apache/cgi-bin">
AllowOverride None
Options +ExecCGI
SetHandler cgi-script
Order allow,deny
Allow from all
</Directory>
<Directory "/usr/local/apache/cgi-bin">
AllowOverride None
Options ExecCGI
AddHandler cgi-script .cgi
<IfModule mod_fastcgi.c>
AddHandler fastcgi-script .fcgi
</IfModule>
Order allow,deny
Allow from all
</Directory>
<Location /protected>
AuthName Pod Bay Doors
AuthType Basic
AuthUserFile /home/alpha-complex/auth/podbayaccess.auth
require user anna betty clara
</Location>
<Location /protected>
AuthName Pod Bay Doors
AuthType Basic
FastCgiAuthenticator cgi-bin/authenticate.fcgi
require user anna betty clara
</Location>
<Location /protected>
AuthName Top Secret
AuthType Basic
FastCgiAccessChecker cgi-bin/accesscheck.fcgi
FastCgiAuthenticator cgi-bin/authenticate.fcgi
FastCgiAuthorizer cgi-bin/authorizer.fcgi
</Location>
--------------------------------------------------------------------------------
LogFormat "%V: %h %l %u %t \"%r\" %>s %b"
LogFormat "%A: %h %l %u %t \"%r\" %>s %b"
--------------------------------------------------------------------------------
Proxy
ProxyRequests on
ProxyRequests off
--------------------------------------------------------------------------------
Configuring Apache As a Proxy
Listen 80
Listen 8080
User httpd
Group httpd
# dynamic servers load modules here...
ServerName www.alpha-complex.com:80
ServerAdmin webmaster@alpha-complex.com
DocumentRoot /home/www/alpha-complex
ErrorLog logs/main_error
TransferLog logs/main_log
<VirtualHost 204.148.170.3:8080>
ServerName proxy.alpha-complex.com
ProxyRequests On
ErrorLog logs/proxy_error
TransferLog logs/proxy_log
</VirtualHost>
<VirtualHost 204.148.170.3:8080>
ServerName proxy.alpha-complex.com
ErrorLog logs/proxy_error
TransferLog logs/proxy_log
ProxyRequests on
CacheRoot /usr/local/apache/cache
# limit use of this proxy to hosts on the local network
<Proxy *>
order deny,allow
deny from all
allow from 204.148.170
</Proxy>
</VirtualHost>
--------------------------------------------------------------------------------
<Directory proxy:*>
... directives for proxy requests only ...
</Directory>
<Proxy *>
... directives for proxy requests only ...
</Proxy>
<Proxy http:*>
... proxy directives for http ...
</Proxy>
<Proxy ftp:*>
... proxy directives for ftp ...
</Proxy>
<Proxy */www.alpha-complex.com/*>
... proxy directives for www.alpha-complex.com ...
</Proxy>
<ProxyMatch www\.alphacomplex\.com>
... proxy directives for www.alpha-complex.com ...
</ProxyMatch>
<ProxyMatch \.html$>
... proxy directives for www.alpha-complex.com ...
</ProxyMatch>
--------------------------------------------------------------------------------
Blocking Sites via the Proxy
ProxyBlock www.badsite.com baddomain.dom badword
--------------------------------------------------------------------------------
Forwarding Proxied URLs
ProxyPass /users/ http://users.alpha-complex.com/
ProxyPass /secure/ http://secure.alpha-complex.com/secure-part/
ProxyPass / http://realwww.intranet.alpha-complex.com
ProxyPassReverse / http://realwww.intranet.alpha-complex.com
<Location /users/>
RequestHeader set X-Proxy-Request yes
ProxyPass http://users.alpha-complex.com/
</Location>
<Location /secure/>
ProxyPass https://externalserver.elsewhere-on-the-internet.com/
</Location>
<Location /secure/>
SSLRequireSSL
ProxyPass http://internal-server.alpha-complex.com/
</Location>
<LocationMatch "\.jsp$">
ProxyPass tomcat.alpha-complex.com
ProxyPassReverse tomcat.alpha-complex.com
</LocationMatch>
--------------------------------------------------------------------------------
Relaying Requests to Remote Proxies
ProxyRemote http http://www.proxyremote.com
ProxyRemote http://www.mainsite.com http://mirror.mainsite.com:8080
ProxyRemote ftp ftp://ftp.ftpmirror.com
ProxyRemote * http://proxy.remote.com
--------------------------------------------------------------------------------
ProxyTimeout 60
--------------------------------------------------------------------------------
Cache
CacheEnable mem /small_images/
CacheEnable fd /large_but_static_documents/
CacheEnable disk /
CacheDisable /dont_cache_this/
CacheRoot /usr/local/apache/proxy/
CacheDirLevels 6
CacheSize 102400
CacheMinFileSize 1024
CacheMaxFileSize 1048576
# trim the cache every 75 minutes
CacheGcInterval 1.25
# trim the cache every 12 minutes
CacheGcInterval 0.2
NoCache *
CacheDisable interactive.alpha-complex.com
CacheDisable uncacheddomain.net
CacheDisable badword
--------------------------------------------------------------------------------
Setting the Memory Cache Size
MCacheSize 10240
MCacheMaxObjectSize 102400
MCacheMinObjectSize 512
--------------------------------------------------------------------------------
# Apache Server Configuration for Clustering Proxy
#
### Basic Server Setup
# The proxy takes the identity of the web site...
ServerName www.alpha-complex.com
# Basic configuration.
# Note that the DocumentRoot is a 'safe' irrelevant value as we don't serve
# anything directly
ServerAdmin webmaster@alpha-complex.com
ServerRoot /usr/local/apache
DocumentRoot /usr/local/apache/proxysite
ErrorLog /usr/local/apache/proxy_error
TransferLog /usr/local/apache/proxy_log
# Choose a non-privileged user and group
User httpd
Group httpd
# Dynamic servers load their modules here...
# Note that if this proxy is only a proxy, we don't need most standard
# modules loaded.
# Don't waste time on things we don't need
HostnameLookups off
# This server is only for proxying so switch off everything else
<Directory />
Options None
AllowOverride None
</Directory>
# Allow a local client to access the server status
<Location />
order allow,deny
deny from all
allow from 127.0.0.1
SetHandler server-status
</Location>
### Part 1 - Rewrite
# switch on URL rewriting
RewriteEngine on
# Define a log for debugging but set the log level to zero to disable it for
# performance
RewriteLog logs/proxy_rewrite
RewriteLogLevel 0
# define the cluster servers map
RewriteMap cluster rnd:/usr/local/apache/rewritemaps/cluster.txt
# rewrite the URL if it matches the web server host
RewriteRule ^http://www\.(.*)$ http://{cluster:www}.$2 [P,L]
# forbid any URL that doesn't match
RewriteRule .* - [F]
### Part 2 - Proxy
ProxyPassReverse / http://www1.alpha-complex.com/
ProxyPassReverse / http://www2.alpha-complex.com/
ProxyPassReverse / http://www3.alpha-complex.com/
ProxyPassReverse / http://www4.alpha-complex.com/
ProxyPassReverse / http://www5.alpha-complex.com/
ProxyPassReverse / http://www6.alpha-complex.com/
# We don't want caching, preferring to let the back end servers take the
# load, but if we did:
#
# Apache 2 only:
CacheOn on
CacheEnable disk /
# Apache 2 and 1.3:
#CacheRoot /usr/local/apache/proxy
#CacheSize 102400
--------------------------------------------------------------------------------
Enabling the Server Status Page
<Location /server/status>
SetHandler server-status
</Location>
<Location /info>
ExtendedStatus on
AddHandler server-status .status
</Location>
--------------------------------------------------------------------------------
Server Info
<Location /server-info>
SetHandler server-info
</Location>
<Location /info>
AddHandler server-status .status
AddHandler server-info .info
</Location>
<Location /server-status>
SetHandler server-status
order deny,allow
deny from all
allow from 127.0.0.1 192.168.1.100
</Location>
<VirtualHost 192.168.2.1:81>
Options None
AllowOveride None
# locations
DocumentRoot /usr/local/apache/status/html
ErrorLog /usr/local/apache/status/logs/error_log
TransferLog /usr/local/apache/status/logs/access_log
# SSI directives
SSLEnable
# Authentication
AuthType Basic
AuthName Status Host
AuthUserFile /usr/local/apache/status/auth/password.file
require valid-user
# host access
order deny,allow
deny from all
allow from 192.168.2.100
# handlers
AddHandler server-status -status
AddHandler server-info -info
# additional info
AddModuleInfo mod_fastcgi "<a href=/docs/mod_fastcgi>Notes</a>"
</VirtualHost>
--------------------------------------------------------------------------------
Auth
<Location /secure>
AuthName <name_of_realm>
AuthType Basic|Digest
Auth<???>UserFile <path_to_users_file_or_db>
Auth<???>GroupFile <path_to_groups_file_or_db>
require valid-user | user <list of users> | group <list of groups>
Auth<???>Authoritative on|off
</Location>
<Location /file_auth>
AuthName "File Authentication"
AuthType Basic
AuthUserFile /usr/local/apache/auth/password.file
AuthGroupFile /usr/local/apache/auth/groups.file
require user user1 user2 group group1 group2
AuthAuthoritative on
</Location>
<Location /dbm_auth>
AuthName "DBM Authentication"
AuthType Basic
AuthDBMUserFile /usr/local/apache/auth/password.dbm
AuthDBMGroupFile /usr/local/apache/auth/groups.dbm
require user user1 user2 group group1 group2
AuthDBMAuthoritative on
</Location>
<Location /anonymous>
AuthName "Guest Access"
AuthType Basic
Anonymous guest visitor cypherpunk
require valid-user
Anonymous_Authoritative on
Anonymous_MustGiveEmail on
Anonymous_VerifyEmail on
Anonymous_LogEmail on
Anonymous_NoUserID off
</Location>
<Location /digestives>
AuthName "Digestion Section"
AuthType Digest
AuthDigestDomain /digestives
AuthDigestFile /usr/local/apache/auth/passwords.md5
AuthDigestGroupFile /usr/local/apache/auth/groups.file
require valid-user
</Location>
--------------------------------------------------------------------------------
LDAP AUTH
<Location /ldapsecure>
AuthName "LDAP Security Barrier"
AuthType Basic
AuthLDAPUrl http://ldap.alphacomplex.com:4444/o=AlphaComplex
AuthLDAPGroupAttribute sector
require valid-user
AuthLDAPAuthoritative on
</Location>
--------------------------------------------------------------------------------
<Location /combined_auth>
AuthName "Combined Authentication"
AuthType Basic
AuthDBMUserFile /usr/local/apache/auth/password.dbm
AuthDBMAuthoritative off
AuthUserFile /usr/local/apache/auth/password.file
</Location>
<Location />
AuthName "Who Are You and Where Do You Come From?"
AuthType Basic
AuthUserFile /usr/local/apache/auth/password.file
require valid-user
order deny,allow
deny from all
allow from www.trustedally.com
Satisfy all
</Location>
--------------------------------------------------------------------------------
Securing Basic Authentication with SSL
<Location /private>
AuthName "Authorized Personnel Only"
AuthType Basic
AuthUserFile auth/personnel.auth
require valid-user
SSLEnable on
SSLRequireSSL
</Location>
--------------------------------------------------------------------------------
Basic SSL Configuration
Listen 80
Listen 443
# Switch on the SSL engine--(for Apache 1.3 Apache-SSL
# use SSLEnable instead)
SSLEngine on
# Specify the server's private key
SSLCertificateKeyFile conf/ssl/www.alpha-complex.com.key
# Specify the certificate for the private key
SSLCertificateFile conf/ssl/www.alpha-complex.com.crt
<VirtualHost 192.168.1.1:443>
ServerName www.alpha-complex.com
DocumentRoot /home/www/alpha-complex
... virtual host directives ...
SSLEngine on
SSLCertificateFile conf/ssl/www.alpha-complex.com.crt
SSLCertificateKeyFile conf/ssl/www.alpha-complex.com.key
</VirtualHost>
<VirtualHost 192.168.1.1:*>
ServerName www.alpha-complex.com
DocumentRoot /home/www/alpha-complex
... virtual host directives ...
</VirtualHost>
<Directory /home/www/alpha-complex/secure/>
SSLrequireSSL
</Directory>
<Location /secure-area/>
SSLRequireSSL
</Location>
<Location /secure-area/non-ssl-browsers/>
order deny,allow
allow from all
Satisfy any
</Location>
<Directory /home/www/alpha-complex/secure/>
SSLRequireSSL
order deny,allow
deny from all
allow from 192.168 www.trusted.com
Satisfy any
</Directory>
--------------------------------------------------------------------------------
SSL and Logging
SSLLog /home/sites/alpha-complex/logs/ssl_log
SSLLog logs/ssl_log
SSLLogLevel warn
SSLLogLevel none
LogFormat "%h %l %u %t \"%r\" %>s %b %{SSL_SESSION_ID}x"
CustomLog logs/ssl_log "%h %t \"%r\" %{SSL_PROTOCL}x %{SSL_SESSION_ID}x %{SSL_CIPHER}%{SSL_USEKEYSIZE}x:%{SSL_ALGKEYSIZE}x" env=HTTPS
--------------------------------------------------------------------------------
SSL and Virtual Hosts
User httpd
Group httpd
# Ports
Listen 80
Listen 443
# main server configuration
ServerName www.alpha-complex.com
ServerAdmin webmaster@alpha-complex.com
DocumentRoot /home/www/alpha-complex
TransferLog logs/access_log
ErrorLog logs/error_log
SSLCertificateFile conf/ssl/www.alpha-complex.com.crt
SSLCertificateKeyFile conf/ssl/www.alpha-complex.com.key
# main server, port 443 (HTTPS)
<VirtualHost 192.168.1.1:443>
SSLEngine on
# server configuration inherited from main server
</VirtualHost>
# main server, port 80 (HTTP)
<VirtualHost 192.168.1.1:80>
# server configuration inherited from main server
</VirtualHost>
# another server, HTTP only, any port
<VirtualHost 192.168.1.2>
... virtual host directives ...
</VirtualHost>
# yet another server, HTTPS only, any port
<VirtualHost 192.168.1.3>
SSLEngine on
... virtual host directives ...
</VirtualHost>
--------------------------------------------------------------------------------
User httpd
Group httpd
# Ports
Listen 80
Listen 443
# main server configuration
ServerName www.alpha-complex.com
ServerAdmin webmaster@alpha-complex.com
DocumentRoot /home/www/alpha-complex
TransferLog logs/access_log
ErrorLog logs/error_log
# uncomment these and remove the first set below for inheritance
#SSLCertificateFile conf/ssl/www.alpha-complex.com.crt
#SSLCertificateKeyFile conf/ssl/www.alpha-complex.com.key
# main server, port 443 (HTTPS)
<VirtualHost 192.168.1.1:443>
SSLEngine on
SSLCertificateFile conf/ssl/www.alpha-complex.com.crt
SSLCertificateKeyFile conf/ssl/www.alpha-complex.com.key
# Server configuration inherited from main server
</VirtualHost>
# another server, HTTPS only, any port
<VirtualHost 192.168.1.3>
SSLEngine on
SSLCertificateFile conf/ssl/www.another.com.crt
SSLCertificateKeyFile conf/ssl/www.another.com.key
... virtual host directives ...
</VirtualHost>
--------------------------------------------------------------------------------
четверг, 28 марта 2013 г.
Cron
# /etc/crontab: system-wide crontab # Unlike any other crontab you don't have to run the `crontab' # command to install the new version when you edit this file # and files in /etc/cron.d. These files also have username fields, # that none of the other crontabs do. SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # m h dom mon dow user command 17 * * * * root cd / && run-parts --report /etc/cron.hourly 25 6 * * * root test -x /usr/sbin/anacron || (cd / && run-parts --report /etc/cron.daily) 47 6 * * 7 root test -x /usr/sbin/anacron || (cd / && run-parts --report /etc/cron.weekly) 52 6 1 * * root test -x /usr/sbin/anacron || (cd / && run-parts --report /etc/cron.monthly) #
* * * * * выполняемая команда
- - - - -
| | | | |
| | | | ----- День недели (0 - 7) (Воскресенье =0 или =7)
| | | ------- Месяц (1 - 12)
| | --------- День (1 - 31)
| ----------- Час (0 - 23)
------------- Минута (0 - 59)
# как обычно, с символа '#' начинаются комментарии # в качестве командного интерпретатора использовать /bin/sh SHELL=/bin/sh # результаты работы отправлять по этому адресу MAILTO=paul@example.org # добавить в PATH PATH=$PATH:$HOME/bin #### Здесь начинаются задания # выполнять каждый день в 0 часов 5 минут, результат складывать в log/daily 5 0 * * * $HOME/bin/daily.job >> $HOME/log/daily 2>&1 # выполнять 1 числа каждого месяца в 14 часов 15 минут 15 14 1 * * $HOME/bin/monthly # каждый рабочий день в 22:00 0 22 * * 1-5 echo "Пора домой" | mail -s "Уже 22:00" john 23 */2 * * * echo "Выполняется в 0:23, 2:23, 4:23 и т. д." 5 4 * * sun echo "Выполняется в 4:05 в воскресенье" 0 0 1 1 * echo "С новым годом!" 15 10,13 * * 1,4 echo "Эта надпись выводится в понедельник и четверг в 10:15 и 13:15" 0-59 * * * * echo "Выполняется ежеминутно" 0-59/2 * * * * echo "Выполняется по четным минутам" 1-59/2 * * * * echo "Выполняется по нечетным минутам" # каждые 5 минут */5 * * * * echo "Прошло пять минут"
# m h dom mon dow command
# Запускаю eMule ночью в 1 час ночи 10 минут
10 1 * * * export DISPLAY=:0 && amule
# Останавливаю eMule утром в 10 часов 10 минут
10 10 * * * export DISPLAY=:0 && killall amule
среда, 27 марта 2013 г.
Запуск MySQL из командной строки
Перейдите в папку, куда был установлен MySQL и введите следующую команду
mysql -u root -p
где -u root это ввод вашего логина (в данном случае это root), а -p это приглашение на ввод вашего пароля.
mysql -u root -p
где -u root это ввод вашего логина (в данном случае это root), а -p это приглашение на ввод вашего пароля.
понедельник, 4 марта 2013 г.
Пример конфигурации Apache
<VirtualHost *:80>
ServerAdmin lufton@gmail.com
ServerName www.db.tci.lan
ServerAlias db.tci.lan
DirectoryIndex index.html index.php
DocumentRoot /home/lufton/public_html/db.tci.lan/public
WSGIScriptAlias / /home/lufton/public_html/db.tci.lan/public/db/mod.wsgi
Alias /js/app.js "/home/lufton/public_html/db.tci.lan/public/db/app.js"
Alias /css "/home/lufton/public_html/db.tci.lan/public/db/css"
<Location "/css">
SetHandler None
Allow from all
</Location>
Alias /js "/home/lufton/public_html/db.tci.lan/public/db/js"
<Location "/js">
SetHandler None
Allow from all
</Location>
Alias /img "/home/lufton/public_html/db.tci.lan/public/db/img"
<Location "/img">
SetHandler None
Allow from all
</Location>
Alias /media "/usr/lib/python2.6/site-packages/django/contrib/admin/media"
<Location "/media">
SetHandler None
Allow from all
</Location>
<Location "/svnmanager">
SetHandler None
Allow from all
</Location>
LogLevel warn
ErrorLog /home/lufton/public_html/db.tci.lan/log/error.log
CustomLog /home/lufton/public_html/db.tci.lan/log/access.log combined
</VirtualHost>
LoadModule python_module modules/mod_python.so
<Directory /home/lufton/public_html/db.tci.lan/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
AddHandler mod_python .py
PythonHandler mod_python.publisher | .py
AddHandler mod_python .psp .psp_
PythonHandler mod_python.psp | .psp .psp_
PythonDebug On
</Directory>
воскресенье, 3 марта 2013 г.
MySQL Шпаргалка по командам
# Comment
---------------------------------------------------------------------------------------------------------
# WORK WITH DATABASE
CREATE DATABASE db_name; (CREATE DATABASE IF NOT EXIST db_name CHARACTER SET utf8;)
SHOW DATABASES;
USE db_name; (ALTER DATABASE db_name CHARACTER SET utf8;)
DROP DATABASE db_name;
---------------------------------------------------------------------------------------------------------
# CREATE TABLE
CREATE TABLE IF NOT EXISTS tb_name (
id int(50) NOT NULL AUTO_INCREMENT,
name VARCHAR(20),
date DATE,
time time,
PRIMARY KEY (id),
FOREIGN KEY (name),
REFERENCES tb_name2 (col1, col2)
);
---------------------------------------------------------------------------------------------------------
# SHOW TABLE
SHOW TABLES;
SHOW COLUMNS FROM tb_name; (SHOW FIELDS FROM tb_name;)
DESCRIBE tb_name;
---------------------------------------------------------------------------------------------------------
# DROP TABLE
DROP TABLE tb_name; (DROP TABLE IF EXISTS tb_name;)
---------------------------------------------------------------------------------------------------------
# SELECT FROM TABLE
SELECT * FROM tb_name;
SELECT col1, col2, col3 FROM tb_name WHERE col1 = 'Bob' AND col2 != '33' AND col3 LIKE '%Tom%' ORDER BY col3 DESC LIMIT 1, 10;
SELECT COUNT(*) FROM tb_name;
---------------------------------------------------------------------------------------------------------
# JOIN TABLE
SELECT * FROM alpha LEFT JOIN beta USING (id);
---------------------------------------------------------------------------------------------------------
# INSERT INTO TABLE
INSERT INTO tb_name (col1, col2) VALUES ('Bob', 'Tom');
---------------------------------------------------------------------------------------------------------
# UPDATE TABLE
UPDATE tb_name SET col1 = 'Tom' WHERE col1 = 'Bob';
---------------------------------------------------------------------------------------------------------
# DELETE FROM TABLE
DELETE FROM tb_name WHERE col1 = 'Bob';
---------------------------------------------------------------------------------------------------------
# ALTER TABLE
ALTER TABLE tb_name ADD COLUMN col1 VARCHAR (20) FIRST; (ALTER TABLE tb_name ADD PRIMARY KEY (id);)
ALTER TABLE tb_name CHANGE old_col new_col VARCHAR (50) AFTER col2; (ALTER TABLE tb_name CHANGE old_col new_col VARCHAR (50) FIRST;)
ALTER TABLE tb_name MODIFY col1 VARCHAR (50) FIRST; (ALTER TABLE tb_name MODIFY col1 VARCHAR (20) AFTER col2;)
ALTER TABLE tb_name DROP COLUMN col1;
---------------------------------------------------------------------------------------------------------
# USER PRIVILEGES
CREATE USER 'bob'@'localhost' IDENTIFIED BY 'password';
SET PASSWORD FOR 'bob'@'localhost' = PASSWORD('new_pass');
GRANT ALL PRIVILEGES ON db_name.* TO 'bob'@'localhost' WITH GRANT OPTION;
GRANT SELECT, INSERT, DELETE ON db_name.* TO 'bob'@'localhost' WITH GRANT OPTION;
REVOKE ALL PRIVILEGES ON db_name.* FROM 'bob'@'localhost';
DROP USER 'bob'@'localhost';
FLUSH PRIVILEGES;
---------------------------------------------------------------------------------------------------------
# COMMON COLUMN TYPES
INT (–2147483648 / 2147483647) (0 / 4294967295)
TINYINT (–128 / 127) (0 / 255)
FLOAT (–3.402823466E+38 / –1.175494351E-38) (1.175494351E-38 / 3.402823466E+38)
DECIMAL, NUMERIC ()
CHAR (1 / 255)
VARCHAR (1 / 255)
DATE ('1000-01-01’ / ‘9999-12-31’) (‘YYYY-MM-DD’ format)
DATETIME (‘1000-01-01 00:00:00’ / ‘9999-12-31 23:59:59’) (‘YYYY-MM-DD HH:MM:SS’ format)
TIMESTAMP (‘1970-01-01 00:00:00’ / year 2037) (YYYYMMDDHHMMSS, YYMMDDHHMMSS, YYYYMMDD or YYMMDD format)
TIME (‘-838:59:59’ / ‘838:59:59’) (‘HH:MM:SS’ format)
YEAR (1901 / 2155) (YYYY format)
TEXT, BLOB (65535 characters)
ENUM (‘val1’, ‘val2’)
SET (‘value1’, ‘value2’)
---------------------------------------------------------------------------------------------------------
# OTHER COLUMN TYPES
SMALLINT (32768 / 32767) (0 / 65535)
MEDIUMINT (–8388608 / 8388607) (0 / 16777215)
BIGINT (–9223372036854775808 / 9223372036854775807) (0 / 18446744073709551615)
DOUBLE, DOUBLE PRECISION, REAL (-1.7976931348623157E+308 / -2.2250738585072014E-308)
TINYTEXT, TINYBLOB (255 characters)
MEDIUMTEXT, MEDIUMBLOB (16777215 characters)
LONGTEXT, LONGBLOB (4294967295 characters)
---------------------------------------------------------------------------------------------------------
# WORK WITH DATABASE
CREATE DATABASE db_name; (CREATE DATABASE IF NOT EXIST db_name CHARACTER SET utf8;)
SHOW DATABASES;
USE db_name; (ALTER DATABASE db_name CHARACTER SET utf8;)
DROP DATABASE db_name;
---------------------------------------------------------------------------------------------------------
# CREATE TABLE
CREATE TABLE IF NOT EXISTS tb_name (
id int(50) NOT NULL AUTO_INCREMENT,
name VARCHAR(20),
date DATE,
time time,
PRIMARY KEY (id),
FOREIGN KEY (name),
REFERENCES tb_name2 (col1, col2)
);
---------------------------------------------------------------------------------------------------------
# SHOW TABLE
SHOW TABLES;
SHOW COLUMNS FROM tb_name; (SHOW FIELDS FROM tb_name;)
DESCRIBE tb_name;
---------------------------------------------------------------------------------------------------------
# DROP TABLE
DROP TABLE tb_name; (DROP TABLE IF EXISTS tb_name;)
---------------------------------------------------------------------------------------------------------
# SELECT FROM TABLE
SELECT * FROM tb_name;
SELECT col1, col2, col3 FROM tb_name WHERE col1 = 'Bob' AND col2 != '33' AND col3 LIKE '%Tom%' ORDER BY col3 DESC LIMIT 1, 10;
SELECT COUNT(*) FROM tb_name;
---------------------------------------------------------------------------------------------------------
# JOIN TABLE
SELECT * FROM alpha LEFT JOIN beta USING (id);
---------------------------------------------------------------------------------------------------------
# INSERT INTO TABLE
INSERT INTO tb_name (col1, col2) VALUES ('Bob', 'Tom');
---------------------------------------------------------------------------------------------------------
# UPDATE TABLE
UPDATE tb_name SET col1 = 'Tom' WHERE col1 = 'Bob';
---------------------------------------------------------------------------------------------------------
# DELETE FROM TABLE
DELETE FROM tb_name WHERE col1 = 'Bob';
---------------------------------------------------------------------------------------------------------
# ALTER TABLE
ALTER TABLE tb_name ADD COLUMN col1 VARCHAR (20) FIRST; (ALTER TABLE tb_name ADD PRIMARY KEY (id);)
ALTER TABLE tb_name CHANGE old_col new_col VARCHAR (50) AFTER col2; (ALTER TABLE tb_name CHANGE old_col new_col VARCHAR (50) FIRST;)
ALTER TABLE tb_name MODIFY col1 VARCHAR (50) FIRST; (ALTER TABLE tb_name MODIFY col1 VARCHAR (20) AFTER col2;)
ALTER TABLE tb_name DROP COLUMN col1;
---------------------------------------------------------------------------------------------------------
# USER PRIVILEGES
CREATE USER 'bob'@'localhost' IDENTIFIED BY 'password';
SET PASSWORD FOR 'bob'@'localhost' = PASSWORD('new_pass');
GRANT ALL PRIVILEGES ON db_name.* TO 'bob'@'localhost' WITH GRANT OPTION;
GRANT SELECT, INSERT, DELETE ON db_name.* TO 'bob'@'localhost' WITH GRANT OPTION;
REVOKE ALL PRIVILEGES ON db_name.* FROM 'bob'@'localhost';
DROP USER 'bob'@'localhost';
FLUSH PRIVILEGES;
---------------------------------------------------------------------------------------------------------
# COMMON COLUMN TYPES
INT (–2147483648 / 2147483647) (0 / 4294967295)
TINYINT (–128 / 127) (0 / 255)
FLOAT (–3.402823466E+38 / –1.175494351E-38) (1.175494351E-38 / 3.402823466E+38)
DECIMAL, NUMERIC ()
CHAR (1 / 255)
VARCHAR (1 / 255)
DATE ('1000-01-01’ / ‘9999-12-31’) (‘YYYY-MM-DD’ format)
DATETIME (‘1000-01-01 00:00:00’ / ‘9999-12-31 23:59:59’) (‘YYYY-MM-DD HH:MM:SS’ format)
TIMESTAMP (‘1970-01-01 00:00:00’ / year 2037) (YYYYMMDDHHMMSS, YYMMDDHHMMSS, YYYYMMDD or YYMMDD format)
TIME (‘-838:59:59’ / ‘838:59:59’) (‘HH:MM:SS’ format)
YEAR (1901 / 2155) (YYYY format)
TEXT, BLOB (65535 characters)
ENUM (‘val1’, ‘val2’)
SET (‘value1’, ‘value2’)
---------------------------------------------------------------------------------------------------------
# OTHER COLUMN TYPES
SMALLINT (32768 / 32767) (0 / 65535)
MEDIUMINT (–8388608 / 8388607) (0 / 16777215)
BIGINT (–9223372036854775808 / 9223372036854775807) (0 / 18446744073709551615)
DOUBLE, DOUBLE PRECISION, REAL (-1.7976931348623157E+308 / -2.2250738585072014E-308)
TINYTEXT, TINYBLOB (255 characters)
MEDIUMTEXT, MEDIUMBLOB (16777215 characters)
LONGTEXT, LONGBLOB (4294967295 characters)
MySQL Наиболее часто используемые команды
Create a database on the sql server.
mysql> create database [databasename];
List all databases on the sql server.
mysql> show databases;
Switch to a database.
mysql> use [db name];
To see all the tables in the db.
mysql> show tables;
To see database's field formats.
mysql> describe [table name];
To delete a db.
mysql> drop database [database name];
To delete a table.
mysql> drop table [table name];
Show all data in a table.
mysql> SELECT * FROM [table name];
Returns the columns and column information pertaining to the designated table.
mysql> show columns from [table name];
Show certain selected rows with the value "whatever".
mysql> SELECT * FROM [table name] WHERE [field name] = "whatever";
Show all records containing the name "Bob" AND the phone number '3444444'.
mysql> SELECT * FROM [table name] WHERE name = "Bob" AND phone_number = '3444444';
Show all records not containing the name "Bob" AND the phone number '3444444' order by the phone_number field.
mysql> SELECT * FROM [table name] WHERE name != "Bob" AND phone_number = '3444444' order by phone_number;
Show all records starting with the letters 'bob' AND the phone number '3444444'.
mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number = '3444444';
Show all records starting with the letters 'bob' AND the phone number '3444444' limit to records 1 through 5.
mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number = '3444444' limit 1,5;
Use a regular expression to find records. Use "REGEXP BINARY" to force case-sensitivity. This finds any record beginning with a.
mysql> SELECT * FROM [table name] WHERE rec RLIKE "^a";
Show unique records.
mysql> SELECT DISTINCT [column name] FROM [table name];
Show selected records sorted in an ascending (asc) or descending (desc).
mysql> SELECT [col1],[col2] FROM [table name] ORDER BY [col2] DESC;
Return number of rows.
mysql> SELECT COUNT(*) FROM [table name];
Sum column.
mysql> SELECT SUM(*) FROM [table name];
Join tables on common columns.
mysql> select lookup.illustrationid, lookup.personid,person.birthday from lookup left join person on lookup.personid=person.personid=statement to join birthday in person table with primary illustration id;
Creating a new user. Login as root. Switch to the MySQL db. Make the user. Update privs.
# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO user (Host,User,Password) VALUES('%','username',PASSWORD('password'));
mysql> flush privileges;
Change a users password from unix shell.
# [mysql dir]/bin/mysqladmin -u username -h hostname.blah.org -p password 'new-password'
Change a users password from MySQL prompt. Login as root. Set the password. Update privs.
# mysql -u root -p
mysql> SET PASSWORD FOR 'user'@'hostname' = PASSWORD('passwordhere');
mysql> flush privileges;
Recover a MySQL root password. Stop the MySQL server process. Start again with no grant tables. Login to MySQL as root. Set new password. Exit MySQL and restart MySQL server.
# /etc/init.d/mysql stop
# mysqld_safe --skip-grant-tables &
# mysql -u root
mysql> use mysql;
mysql> update user set password=PASSWORD("newrootpassword") where User='root';
mysql> flush privileges;
mysql> quit
# /etc/init.d/mysql stop
# /etc/init.d/mysql start
Set a root password if there is on root password.
# mysqladmin -u root password newpassword
Update a root password.
# mysqladmin -u root -p oldpassword newpassword
Allow the user "bob" to connect to the server from localhost using the password "passwd". Login as root. Switch to the MySQL db. Give privs. Update privs.
# mysql -u root -p
mysql> use mysql;
mysql> grant usage on *.* to bob@localhost identified by 'passwd';
mysql> flush privileges;
Give user privilages for a db. Login as root. Switch to the MySQL db. Grant privs. Update privs.
# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO db (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv) VALUES ('%','databasename','username','Y','Y','Y','Y','Y','N');
mysql> flush privileges;
or
mysql> grant all privileges on databasename.* to username@localhost;
mysql> flush privileges;
To update info already in a table.
mysql> UPDATE [table name] SET Select_priv = 'Y',Insert_priv = 'Y',Update_priv = 'Y' where [field name] = 'user';
Delete a row(s) from a table.
mysql> DELETE from [table name] where [field name] = 'whatever';
Update database permissions/privilages.
mysql> flush privileges;
Delete a column.
mysql> alter table [table name] drop column [column name];
Add a new column to db.
mysql> alter table [table name] add column [new column name] varchar (20);
Change column name.
mysql> alter table [table name] change [old column name] [new column name] varchar (50);
Make a unique column so you get no dupes.
mysql> alter table [table name] add unique ([column name]);
Make a column bigger.
mysql> alter table [table name] modify [column name] VARCHAR(3);
Delete unique from table.
mysql> alter table [table name] drop index [colmn name];
Load a CSV file into a table.
mysql> LOAD DATA INFILE '/tmp/filename.csv' replace INTO TABLE [table name] FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (field1,field2,field3);
Dump all databases for backup. Backup file is sql commands to recreate all db's.
# [mysql dir]/bin/mysqldump -u root -ppassword --opt >/tmp/alldatabases.sql
Dump one database for backup.
# [mysql dir]/bin/mysqldump -u username -ppassword --databases databasename >/tmp/databasename.sql
Dump a table from a database.
# [mysql dir]/bin/mysqldump -c -u username -ppassword databasename tablename > /tmp/databasename.tablename.sql
Restore database (or database table) from backup.
# [mysql dir]/bin/mysql -u username -ppassword databasename < /tmp/databasename.sql
Create Table Example 1.
mysql> CREATE TABLE [table name] (firstname VARCHAR(20), middleinitial VARCHAR(3), lastname VARCHAR(35),suffix VARCHAR(3),officeid VARCHAR(10),userid VARCHAR(15),username VARCHAR(8),email VARCHAR(35),phone VARCHAR(25), groups VARCHAR(15),datestamp DATE,timestamp time,pgpemail VARCHAR(255));
Create Table Example 2.
mysql> create table [table name] (personid int(50) not null auto_increment primary key,firstname varchar(35),middlename varchar(50),lastnamevarchar(50) default 'bato');
Оригинал: pantz.org/software/mysql/mysqlcommands.html
mysql> create database [databasename];
List all databases on the sql server.
mysql> show databases;
Switch to a database.
mysql> use [db name];
To see all the tables in the db.
mysql> show tables;
To see database's field formats.
mysql> describe [table name];
To delete a db.
mysql> drop database [database name];
To delete a table.
mysql> drop table [table name];
Show all data in a table.
mysql> SELECT * FROM [table name];
Returns the columns and column information pertaining to the designated table.
mysql> show columns from [table name];
Show certain selected rows with the value "whatever".
mysql> SELECT * FROM [table name] WHERE [field name] = "whatever";
Show all records containing the name "Bob" AND the phone number '3444444'.
mysql> SELECT * FROM [table name] WHERE name = "Bob" AND phone_number = '3444444';
Show all records not containing the name "Bob" AND the phone number '3444444' order by the phone_number field.
mysql> SELECT * FROM [table name] WHERE name != "Bob" AND phone_number = '3444444' order by phone_number;
Show all records starting with the letters 'bob' AND the phone number '3444444'.
mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number = '3444444';
Show all records starting with the letters 'bob' AND the phone number '3444444' limit to records 1 through 5.
mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number = '3444444' limit 1,5;
Use a regular expression to find records. Use "REGEXP BINARY" to force case-sensitivity. This finds any record beginning with a.
mysql> SELECT * FROM [table name] WHERE rec RLIKE "^a";
Show unique records.
mysql> SELECT DISTINCT [column name] FROM [table name];
Show selected records sorted in an ascending (asc) or descending (desc).
mysql> SELECT [col1],[col2] FROM [table name] ORDER BY [col2] DESC;
Return number of rows.
mysql> SELECT COUNT(*) FROM [table name];
Sum column.
mysql> SELECT SUM(*) FROM [table name];
Join tables on common columns.
mysql> select lookup.illustrationid, lookup.personid,person.birthday from lookup left join person on lookup.personid=person.personid=statement to join birthday in person table with primary illustration id;
Creating a new user. Login as root. Switch to the MySQL db. Make the user. Update privs.
# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO user (Host,User,Password) VALUES('%','username',PASSWORD('password'));
mysql> flush privileges;
Change a users password from unix shell.
# [mysql dir]/bin/mysqladmin -u username -h hostname.blah.org -p password 'new-password'
Change a users password from MySQL prompt. Login as root. Set the password. Update privs.
# mysql -u root -p
mysql> SET PASSWORD FOR 'user'@'hostname' = PASSWORD('passwordhere');
mysql> flush privileges;
Recover a MySQL root password. Stop the MySQL server process. Start again with no grant tables. Login to MySQL as root. Set new password. Exit MySQL and restart MySQL server.
# /etc/init.d/mysql stop
# mysqld_safe --skip-grant-tables &
# mysql -u root
mysql> use mysql;
mysql> update user set password=PASSWORD("newrootpassword") where User='root';
mysql> flush privileges;
mysql> quit
# /etc/init.d/mysql stop
# /etc/init.d/mysql start
Set a root password if there is on root password.
# mysqladmin -u root password newpassword
Update a root password.
# mysqladmin -u root -p oldpassword newpassword
Allow the user "bob" to connect to the server from localhost using the password "passwd". Login as root. Switch to the MySQL db. Give privs. Update privs.
# mysql -u root -p
mysql> use mysql;
mysql> grant usage on *.* to bob@localhost identified by 'passwd';
mysql> flush privileges;
Give user privilages for a db. Login as root. Switch to the MySQL db. Grant privs. Update privs.
# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO db (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv) VALUES ('%','databasename','username','Y','Y','Y','Y','Y','N');
mysql> flush privileges;
or
mysql> grant all privileges on databasename.* to username@localhost;
mysql> flush privileges;
To update info already in a table.
mysql> UPDATE [table name] SET Select_priv = 'Y',Insert_priv = 'Y',Update_priv = 'Y' where [field name] = 'user';
Delete a row(s) from a table.
mysql> DELETE from [table name] where [field name] = 'whatever';
Update database permissions/privilages.
mysql> flush privileges;
Delete a column.
mysql> alter table [table name] drop column [column name];
Add a new column to db.
mysql> alter table [table name] add column [new column name] varchar (20);
Change column name.
mysql> alter table [table name] change [old column name] [new column name] varchar (50);
Make a unique column so you get no dupes.
mysql> alter table [table name] add unique ([column name]);
Make a column bigger.
mysql> alter table [table name] modify [column name] VARCHAR(3);
Delete unique from table.
mysql> alter table [table name] drop index [colmn name];
Load a CSV file into a table.
mysql> LOAD DATA INFILE '/tmp/filename.csv' replace INTO TABLE [table name] FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (field1,field2,field3);
Dump all databases for backup. Backup file is sql commands to recreate all db's.
# [mysql dir]/bin/mysqldump -u root -ppassword --opt >/tmp/alldatabases.sql
Dump one database for backup.
# [mysql dir]/bin/mysqldump -u username -ppassword --databases databasename >/tmp/databasename.sql
Dump a table from a database.
# [mysql dir]/bin/mysqldump -c -u username -ppassword databasename tablename > /tmp/databasename.tablename.sql
Restore database (or database table) from backup.
# [mysql dir]/bin/mysql -u username -ppassword databasename < /tmp/databasename.sql
Create Table Example 1.
mysql> CREATE TABLE [table name] (firstname VARCHAR(20), middleinitial VARCHAR(3), lastname VARCHAR(35),suffix VARCHAR(3),officeid VARCHAR(10),userid VARCHAR(15),username VARCHAR(8),email VARCHAR(35),phone VARCHAR(25), groups VARCHAR(15),datestamp DATE,timestamp time,pgpemail VARCHAR(255));
Create Table Example 2.
mysql> create table [table name] (personid int(50) not null auto_increment primary key,firstname varchar(35),middlename varchar(50),lastnamevarchar(50) default 'bato');
Оригинал: pantz.org/software/mysql/mysqlcommands.html
Подписаться на:
Комментарии (Atom)