Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 43 total  RSS 

Deploying on a passenger / mod_rails host with capistrano

// add this to deploy.rb

namespace :mod_rails do
  desc <<-DESC
  Restart the application altering tmp/restart.txt for mod_rails.
  DESC
  task :restart, :roles => :app do
    run "touch  #{release_path}/tmp/restart.txt"
  end
end

namespace :deploy do
  %w(start restart).each { |name| task name, :roles => :app do mod_rails.restart end }
end

Split Apache logs according to GeoIP country

// Split Apache logs according to GeoIP country

#!/usr/bin/perl

# $Id$

# Split Apache logs according to GeoIP country

use strict;
use warnings;

## no critic (ValuesAndExpressions::RequireInterpolationOfMetachars)
our ($VERSION) = '$Revision$' =~ m{ \$Revision: \s+ (\S+) }xms;
## use critic

use Geo::IP;

my $gi = Geo::IP->open('/usr/local/share/GeoIP/GeoIPCity.dat', GEOIP_STANDARD);

my @logs = @ARGV;

my %record_for;

foreach my $log (@logs) {
    die "Can't read $log\n" if !-r $log;
    
    my %fh_for;
    my $num_lines_parsed = 0;
    
    my $log_fh;
    if ($log =~ m/ \.gz \z /xms) {
        open $log_fh, "gzip -cd $log |" or die "Can't open gzip pipe\n";
    }
    else {
        open $log_fh, '<', $log or die "Can't open $log\n";
    }
    
    my $log_base = $log;
    $log_base =~ s/ \.gz \z //xms;
    
    while (my $line = <$log_fh>) {
        $num_lines_parsed++;
        if (!($num_lines_parsed % 1000)) {
            print STDERR "Parsed $num_lines_parsed lines of $log\n";
        }
        
        my ($host) = $line =~ m/ \A (\S+) \s /xms;
        
        if (!exists $record_for{$host}) {
            my $record = $gi->record_by_name($host);
            $record_for{$host} = $record || 0;
        }
        
        my $country = 'unknown';
        if (exists $record_for{$host} && $record_for{$host}) {
            $country = lc($record_for{$host}->country_name());
            $country =~ s/\W+/_/gxms;
        }
        
        if (!exists $fh_for{$country}) {
            open $fh_for{$country}, '>', "$log_base.$country.out"
                or die "Can't write to $log_base.$country.out\n";
        }
        
        print {$fh_for{$country}} $line;
    }
    
    foreach my $fh (values %fh_for) {
        close $fh;
    }
    
    close $log_fh;
}

Apache rewrite rules

Pass all requests for non-existing files or directories to index.php
RewriteCond        %{REQUEST_FILENAME}        !-f                
RewriteCond        %{REQUEST_FILENAME}        !-d
RewriteRule        ^(.*)$                    index.php        [L]

apache dir config

// description of your code here

Alias /swf1  "E:/flexprojects/t2/deploy"
    <Directory "E:/flexprojects/t2/deploy">
		AllowOverride   None  
        Order   allow,deny  
        Allow   from   all   
	</Directory>

Using Apache with RewriteMap and a text file

This code will read a text file using Apache then upon a user request, look for a url containing /l/ eg. http://mysite.com/l/digg and rewrite the URL in full eg. http://mysite.com/gwd/feed/digg.html . The example file is shown here for completeness.

RewriteMap uses a text file as a convenient alternative for the administrator when declaring many rewrite rules. Code based on the article from ONLamp.com - A Day in the Life of #Apache http://urltea.com/1vwb


<file name="links.txt" location="/var/www/localhost/">
scotsman /gwd/feed/scotsman.html
digg /gwd/feed/digg.html
</file>

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteMap links txt:/var/www/localhost/links.txt
RewriteRule ^/l/(.*) ${links:$1|http://mysite.com/} [R]
</IfModule>



Note: The [R] at the end of RewriteRule means redirect, to have a clean url simply remove that switch.

*update 15-Feb-08 *
Restart Apache rather reloading the module when switching redirection on or off for a RewriteRule. The Apache version 2.2.6 (Unix) didn't pick up my settings correctly when I tried /etc/init.d/apache2 reload, instead I needed to use /etc/init.d/apache2 restart.

A simple mod_rewrite example

Rewrite a long url as a short easy to remember url with mod_rewrite. Place this code in httpd.conf or the virtual hosts file. Original code from sitepoint - mod_rewrite: A Beginner's Guide to URL Rewriting http://urltea.com/1v6d .

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^/shortcut$ /complicated/and/way/too/long/url/here
</IfModule>

Mongrel and Apache fun with Capistrano 2.0

I got the Mongrel recipes from somewhere else -- I sadly don't remember where -- and modified them a bit.

namespace :deploy do
  namespace :mongrel do
    [ :stop, :start, :restart ].each do |t|
      desc "#{t.to_s.capitalize} the mongrel appserver"
      task t, :roles => :app do
        run "mongrel_rails cluster::#{t.to_s} --clean -C #{mongrel_conf}"
      end
    end
  end
  
  namespace :apache do
    desc "Start Apache"
    task :start, :roles => :web do
      sudo "/etc/init.d/httpd start > /dev/null"
    end

    desc "Stop Apache"
    task :stop, :roles => :web do
      sudo "/etc/init.d/httpd stop > /dev/null"
    end

    desc "Restart Apache"
    task :restart, :roles => :web do
      sudo "/etc/init.d/httpd restart > /dev/null"
    end
  end

  desc "Custom restart task for mongrel cluster"
  task :restart do
    deploy.mongrel.restart
    deploy.apache.restart
  end

  desc "Custom start task for mongrel cluster"
  task :start, :roles => :app do
    deploy.mongrel.start
    deploy.apache.start
  end

  desc "Custom stop task for mongrel cluster"
  task :stop, :roles => :app do
    deploy.apache.stop
    deploy.mongrel.stop
  end

end

Make sure your site (or directory) is SSL encrypted

Need a simple way to make sure all http requests get redirected to https?
This apache config snippet will redirect all requests at or below the specified location to its https equivilant.

<Location "/">
        RewriteEngine on
        Options +FollowSymLinks
        Allow from all
        RewriteCond %{SERVER_PORT} !^443$
        RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]
</Location>

apache configuration for 1 application serving requests from mulitple (4) domains

// One rails application serving 4 domains via mongrel + apache2.2 proxy

#
# Proxy Server directives. Uncomment the following lines to
# enable the proxy server:
#
<IfModule mod_proxy.c>
ProxyRequests Off

<Proxy *>
    Order deny,allow
    Deny from all
    Allow from all
</Proxy>

#ProxyPass / http://127.0.0.1:8000/dl
#ProxyPassReverse / http://127.0.0.1:8000/dl
#ProxyPreserveHost On


</IfModule>
# End of proxy directives.

Listen 8080
<VirtualHost *:8080>
  <Location />
    SetHandler balancer-manager
    Deny from all
    Allow from localhost
  </Location>
</VirtualHost>

<Proxy balancer://mongrel_cluster>
    BalancerMember http://127.0.0.1:8000
    BalancerMember http://127.0.0.1:8001
    BalancerMember http://127.0.0.1:8002
</Proxy>

<VirtualHost *:80>
Include /home/WEBSITEAPP/current/config/apache/dod.conf

ServerName www.WEBSITENAME4.com

    ErrorLog logs/WEBSITENAME4_errors_log
    CustomLog logs/WEBSITENAME4_log combined
</VirtualHost>

<VirtualHost *:80>
Include /home/WEBSITEAPP/current/config/apache/dl.conf

ServerName www.WEBSITENAME0.com

    ErrorLog logs/WEBSITENAME0_errors_log
    CustomLog logs/WEBSITENAME0_log combined
</VirtualHost>

<VirtualHost *:80>
Include /home/WEBSITEAPP/current/config/apache/pf.conf

ServerName test.WEBSITENAME1.com

    ErrorLog logs/WEBSITENAME1_errors_log
    CustomLog logs/WEBSITENAME1_log combined
</VirtualHost>

<VirtualHost *:80>
Include /home/WEBSITEAPP/current/config/apache/dag.conf

ServerName www.WEBSITENAME2.com

    ErrorLog logs/WEBSITENAME_errors_log
    CustomLog logs/WEBSITENAME_log combined
</VirtualHost>





example of one of the configuration of the virtual hosts
-bash-3.00$ cat /home/WEBSITEAPP/current/config/apache/dod.conf

ServerName WEBSITENAME.com
ServerAlias www.WEBSITENAME.com test.WEBSITENAME.com 

# Pass other requests to mongrel instance
ProxyPass / http://127.0.0.1:8000/
ProxyPassReverse / http://127.0.0.1:8000/
ProxyPreserveHost On
ProxyRequests Off

# Do not allow open proxying, allow only requests starting with a /
<LocationMatch "^[^/]">
        Deny from all
</LocationMatch>


DocumentRoot /home/WEBSITEAPP/current/public

  <Directory "/home/WEBSITEAPP/current/public">
    Options FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
  </Directory>

  RewriteEngine On

  # Uncomment for rewrite debugging
  RewriteLog logs/myapp_rewrite_log
  RewriteLogLevel 9 


  # Check for maintenance file and redirect all requests
  #  ( this is for use with Capistrano's disable_web task )
  RewriteCond %{DOCUMENT_ROOT}/system/maintenance.html -f
  RewriteCond %{SCRIPT_FILENAME} !maintenance.html
  RewriteRule ^.*$ /system/maintenance.html [L]

  # Rewrite index to check for static
#  RewriteRule ^/$ /index.html [QSA] 
  RewriteRule ^/$ /dod/navigation [QSA] 
#  RewriteRule ^/$ /dl/navigation [L] 

  # Rewrite to check for Rails cached page
#  RewriteRule ^([^.]+)$ $1.html [QSA]


  # Redirect all non-static requests to cluster
  RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
#  RewriteRule ^/(.*)$ balancer://mongrel_cluster%{REQUEST_URI} [P,QSA,L]
  RewriteRule ^/(.*)$ balancer://mongrel_cluster/$1 [P,QSA,L]
#  RewriteRule "^/(.*)" "http://localhost:8001/$1" [P,QSA,L]

  # Deflate
  AddOutputFilterByType DEFLATE text/html text/plain text/css
  # ... text/xml application/xml application/xhtml+xml text/javascript 
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

  # Uncomment for deflate debugging
  #DeflateFilterNote Input input_info
  #DeflateFilterNote Output output_info
  #DeflateFilterNote Ratio ratio_info
  #LogFormat '"%r" %{output_info}n/%{input_info}n (%{ratio_info}n%%)' deflate
  #CustomLog logs/myapp_deflate_log deflate

Glossword WAMP source code (NSIS)

// NSIS (http://nsis.sourceforge.net/)
// Glossword WAMP (http://sourceforge.net/projects/glossword/)
// Apache, MySQL and PHP are stored in archive usr.exe, directory /usr/local
// phpMyAdmin is in archive htdocs.exe, directory /htdocs/phpmyadmin
// Additionaly you need files with phrases: English.nsh and Russian.nsh
// ------------------------------------------
// English.nsh:
// LangString SECT_01 ${LANG_ENGLISH} "Glossword ${PRODUCT_VERSION}"
// LangString TXT_02 ${LANG_ENGLISH} "Thank you for installing Glossword.\r\nFor news and updates go to http://sourceforge.net/projects/glossword/"
// LangString DESC_SecGw ${LANG_ENGLISH} "Glossword program core files."
// ------------------------------------------
// install.bat
// @echo on
// cls
// SET ipath=%1
// cd "%ipath%/usr/local/apache2/bin"
// httpd.exe -k install -n Apache2_GW
// httpd.exe -k start -n Apache2_GW
// cd "%ipath%/usr/local/mysql5/bin"
// mysqld-nt.exe --install MySQL50_GW --defaults-file="%ipath%/usr/local/mysql5/bin/my-custom.cnf"
// net start MySQL50_GW
// ------------------------------------------
// uninstall.bat
// @echo off
// cls
// SET ipath=%1
// cd "%ipath%/usr/local/apache2/bin"
// httpd.exe -k stop -n Apache2_GW
// httpd.exe -k uninstall -n Apache2_GW
// net stop MySQL50_GW
// cd "%ipath%/usr/local/mysql5/bin"
// mysqld-nt.exe --remove MySQL50_GW
// ------------------------------------------
// unpack.bat
// @echo off
// usr.exe -y
// htdocs.exe -y
// del usr.exe
// del htdocs.exe
// del unpack.bat


Now you can create your own WAMP package.

; Glossword Desktop edition: Apache, MySQL, PHP
; Written by Dmitry Shilnikov (c) 2002-2007
; tty01@rambler.ru
;--------------------------------
;Include Modern UI

!include "MUI.nsh"

; replace in file with count of changes
!include "FileFunc.nsh"

;--------------------------------
;Custom variables

!define PRODUCT_NAME "Apache, MySQL, PHP"
!define PRODUCT_VERSION "Apache/2.2.4, MySQL 5.0.41-community-nt, PHP 5.2.3 for Windows"
!define DIR_SRC "."
!define THIS_DIR_INSTALLTO "Glossword-WAMP"

;--------------------------------
;General

Name "${PRODUCT_NAME}"
OutFile "glossword-wamp.exe"

;Folder selection page
InstallDir "$PROGRAMFILES\Glossword-WAMP"

;--------------------------------
;Interface Settings

!define MUI_ABORTWARNING
!define MUI_UI ${NSISDIR}\Contrib\UIs\modern.exe
!define MUI_ICON ${DIR_SRC}\install\gw_new.ico
!define MUI_UNICON ${DIR_SRC}\install\gw_remove.ico
!define MUI_FINISHPAGE_TEXT $(TXT_02)

;--------------------------------
;Pages

!insertmacro MUI_PAGE_WELCOME
!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_FINISH

;Uninstaller pages
!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES

;--------------------------------
;Languages

!insertmacro MUI_LANGUAGE "English"
!insertmacro MUI_LANGUAGE "Russian"

;--------------------------------
;Installer Sections

Section "$(SECT_01)" SecGw

SetDetailsPrint textonly
DetailPrint "Installing server files..."
SetOverwrite ifnewer

DetailPrint "htdocs..."
CreateDirectory "$INSTDIR\htdocs"
CreateDirectory "$INSTDIR\htdocs\glossword"

SetOutPath "$INSTDIR"
File "usr.exe"
File "htdocs.exe"
File "unpack.bat"
File "install.bat"
File "uninstall.bat"
File "localhost.url"
File "phpinfo.url"
File "phpmyadmin.url"
File "news.url"
File "glossword-wamp224_5041_523.txt"

ExecWait '"unpack.bat"'

SetOutPath "$INSTDIR"
; change configuraiton files
DetailPrint "httpd.conf..."
ClearErrors
FileOpen $0 "$INSTDIR\usr\local\apache2\conf\httpd.conf" "r"
GetTempFileName $R0
FileOpen $1 $R0 "w"
loop1:
FileRead $0 $2
IfErrors done1
StrCmp $2 "# Created by install$\r$\n" 0 +2
StrCpy $2 "# Created by glossword-amp.exe$\r$\n"
StrCmp $2 "DocumentRoot $\"E:/usr/httpdocs/svn/Glossword Desktop/htdocs$\"$\r$\n" 0 +2
StrCpy $2 "DocumentRoot $\"$INSTDIR\htdocs$\"$\r$\n"
StrCmp $2 "ServerRoot $\"E:/usr/httpdocs/svn/Glossword Desktop/usr/local/apache2$\"$\r$\n" 0 +2
StrCpy $2 "ServerRoot $\"$INSTDIR\usr\local\apache2$\"$\r$\n"
FileWrite $1 $2
Goto loop1
done1:
FileClose $0
FileClose $1
Delete "$INSTDIR\usr\local\apache2\conf\httpd.conf"
CopyFiles /SILENT $R0 "$INSTDIR\usr\local\apache2\conf\httpd.conf"
Delete $R0
;
DetailPrint "my-custom.cnf..."
ClearErrors
FileOpen $0 "$INSTDIR\usr\local\mysql5\bin\my-custom.cnf" "r"
GetTempFileName $R0
FileOpen $1 $R0 "w"
loop2:
FileRead $0 $2
IfErrors done2
StrCmp $2 "basedir=$\"../mysql5/$\"$\r$\n" 0 +2
StrCpy $2 "basedir=$\"$INSTDIR\usr\local\mysql5\$\"$\r$\n"
StrCmp $2 "datadir=$\"../mysql5/data/$\"$\r$\n" 0 +2
StrCpy $2 "datadir=$\"$INSTDIR\usr\local\mysql5\data\$\"$\r$\n"
FileWrite $1 $2
Goto loop2
done2:
FileClose $0
FileClose $1
Delete "$INSTDIR\usr\local\mysql5\bin\my-custom.cnf"
CopyFiles /SILENT $R0 "$INSTDIR\usr\local\mysql5\bin\my-custom.cnf"
Delete $R0
;
DetailPrint "php.ini..."
ClearErrors
FileOpen $0 "$INSTDIR\usr\local\php5\php.ini" "r"
GetTempFileName $R0
FileOpen $1 $R0 "w"
loop5:
FileRead $0 $2
IfErrors done5
StrCmp $2 "extension_dir = $\"../../php5/ext$\"$\r$\n" 0 +2
StrCpy $2 "extension_dir = $\"$INSTDIR\usr\local\php5\ext$\"$\r$\n"
StrCmp $2 "session.save_path = $\"c:/temp$\"$\r$\n" 0 +2
StrCpy $2 "session.save_path = $\"$TEMP$\"$\r$\n"
FileWrite $1 $2
Goto loop5
done5:
FileClose $0
FileClose $1
Delete "$INSTDIR\usr\local\php5\php.ini"
CopyFiles /SILENT $R0 "$INSTDIR\usr\local\php5\php.ini"
Delete $R0
;
DetailPrint "install.bat..."
ClearErrors
FileOpen $0 "$INSTDIR\install.bat" "r"
GetTempFileName $R0
FileOpen $1 $R0 "w"
loop3:
FileRead $0 $2
IfErrors done3
StrCmp $2 "set ipath=%1$\r$\n" 0 +2
StrCpy $2 "set ipath=$INSTDIR$\r$\n"
FileWrite $1 $2
Goto loop3
done3:
FileClose $0
FileClose $1
Delete "$INSTDIR\install.bat"
CopyFiles /SILENT $R0 "$INSTDIR\install.bat"
Delete $R0
;
DetailPrint "uninstall.bat..."
ClearErrors
FileOpen $0 "$INSTDIR\uninstall.bat" "r"
GetTempFileName $R0
FileOpen $1 $R0 "w"
loop4:
FileRead $0 $2
IfErrors done4
StrCmp $2 "set ipath=%1$\r$\n" 0 +2
StrCpy $2 "set ipath=$INSTDIR$\r$\n"
FileWrite $1 $2
Goto loop4
done4:
FileClose $0
FileClose $1
Delete "$INSTDIR\uninstall.bat"
CopyFiles /SILENT $R0 "$INSTDIR\uninstall.bat"
Delete $R0
ExecWait '"install.bat"'
;nsExec::ExecToStack '"install.bat"'

SetOverwrite off

CreateDirectory "$SMPROGRAMS\${THIS_DIR_INSTALLTO}"
CreateShortCut "$SMPROGRAMS\${THIS_DIR_INSTALLTO}\Glossword at localhost.lnk" "$INSTDIR\localhost.url"
CreateShortCut "$SMPROGRAMS\${THIS_DIR_INSTALLTO}\Glossword development news.lnk" "$INSTDIR\news.url"
CreateShortCut "$SMPROGRAMS\${THIS_DIR_INSTALLTO}\phpinfo().lnk" "$INSTDIR\phpinfo.url"
CreateShortCut "$SMPROGRAMS\${THIS_DIR_INSTALLTO}\phpMyAdmin.lnk" "$INSTDIR\phpmyadmin.url"
CreateShortCut "$SMPROGRAMS\${THIS_DIR_INSTALLTO}\Apache Monitor.lnk" "$INSTDIR\usr\local\apache2\bin\ApacheMonitor.exe"
CreateShortCut "$SMPROGRAMS\${THIS_DIR_INSTALLTO}\Remove Glossword WAMP.lnk" "$INSTDIR\uninstall.exe"
CreateShortCut "$SMPROGRAMS\${THIS_DIR_INSTALLTO}\Release notes.lnk" "$INSTDIR\glossword-wamp224_5041_523.txt"

WriteUninstaller "$INSTDIR\uninstall.exe"
SectionEnd


;--------------------------------
;Descriptions

!include "${DIR_SRC}\install\English.nsh"
!include "${DIR_SRC}\install\Russian.nsh"

!insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN
!insertmacro MUI_DESCRIPTION_TEXT ${SecGw} $(DESC_SecGw)
!insertmacro MUI_FUNCTION_DESCRIPTION_END

;--------------------------------
; Functions

Function .onInit
!insertmacro MUI_LANGDLL_DISPLAY
FunctionEnd

;--------------------------------
;Uninstaller Section

Section Uninstall

SetOutPath "$INSTDIR"
ExecWait '"uninstall.bat"'

SetShellVarContext current
Delete "$SMPROGRAMS\${THIS_DIR_INSTALLTO}\Remove Glossword WAMP.lnk"
Delete "$SMPROGRAMS\${THIS_DIR_INSTALLTO}\Apache Monitor.lnk"
Delete "$SMPROGRAMS\${THIS_DIR_INSTALLTO}\Glossword at localhost.lnk"
Delete "$SMPROGRAMS\${THIS_DIR_INSTALLTO}\Glossword development news.lnk"
Delete "$SMPROGRAMS\${THIS_DIR_INSTALLTO}\phpinfo().lnk"
Delete "$SMPROGRAMS\${THIS_DIR_INSTALLTO}\phpMyAdmin.lnk"
Delete "$SMPROGRAMS\${THIS_DIR_INSTALLTO}\Release Notes.lnk"
RMDir /r "$SMPROGRAMS\${THIS_DIR_INSTALLTO}"
RMDir /r "$INSTDIR\usr\local\apache2"
RMDir /r "$INSTDIR\usr\local\php5"
RMDir /r "$INSTDIR\usr\local\mysql5\bin"
RMDir /r "$INSTDIR\usr\local\mysql5\share"
RMDir /r "$INSTDIR\htdocs\phpmyadmin"
Delete "$INSTDIR\install.bat"
Delete "$INSTDIR\uninstall.bat"
Delete "$INSTDIR\glossword-wamp224_5041_523.txt"
Delete "$INSTDIR\localhost.url"
Delete "$INSTDIR\phpinfo.url"
Delete "$INSTDIR\phpmyadmin.url"

;RMDir /r "$INSTDIR"
SetAutoClose true

SectionEnd
« Newer Snippets
Older Snippets »
Showing 1-10 of 43 total  RSS