Apache Virtual Hosts Examples

If you want multiple VirtualHosts on the same IP address and port you are going to require a NamedVirtualHost directive.

If you are configuring multiple virtual hosts on different IP addresses but all on the same port you do NOT require the NamedVirtualHost directive.

If you are configuring multiple virtual hosts on the same IP address but different ports you do not require the NamedVirtualHost directive.

NOTE: You can run a combination of all of the above if you wish!

You can specify a range of port to listen on as well.

Listen 40000:40500
Advertisements

Apache RewriteRule

This cheat sheet was taken from here: http://borkweb.com/story/apache-rewrite-cheatsheet

Examples:

Site has moved to a new domain:

RewriteCond   %{HTTP_HOST}   ^www.domain.com$   [NC]

RewriteRule ^(.*)$ http://www.domain2.com/$1 [R=301,L]

Page has moved temporarily, domain.com/page.html to domain.com/new_page.html

RewriteRule ^page.html$ new_page.html [R,NC,L]

Block referrer spam

RewriteCond %{HTTP_REFERRER} (weight) [NC,OR]

RewriteCond %{HTTP_REFERRER} (drugs) [NC]

RewriteRule .* – [F]

I wanted to redirect a <Location …> directive. I had SSLRequireSSL above the redirect and Apache processes that requirement before it ever got to my redirect statements. I was able to get it working by commenting the SSLRequireSSL and adding the following statements

RewriteEngine on
RewriteBase /
RewriteCond %{HTTPS} !=on
RewriteRule (.*) https://%{SERVER_NAME}/%{REQUEST_URI} [L]

When you browse to a website that requires SSL (https://) you will get a forbidden message. Instead I wanted to automatically redirect the un-secure website to the secure one. I added the following to my <Directory> directive for phpMyAdmin.

RewriteEngine On
RewriteBase /
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^.*$ https://%{SERVER_NAME}/%{REQUEST_URI} [L,R]

Regular Expression Syntax

^ Start of string
$ End of string
. Any single character
(a|b) a or b
(…) Group section
[abc] Item in range (a or b or c)
[^abc] Not in range (not a or b or c)
a? Zero or one of a
a* Zero or more of a
a+ One or more of a
a{3} Exactly 3 of a
a{3,} 3 or more of a
a{3,6} Between 3 and 6 of a
!(pattern) “Not” prefix. Apply rule when URL does not match pattern

RewriteRule FLAGS

I’m going to go a little deeper in this list than what the cheat sheet does as I tend to need a little more of a description on what each flag does (all descriptions are lifted without remorse fromApache.org)…not just the short definition.

R[=code] Redirect to new URL, with optional code (see below). Prefix Substitution with http://thishost%5B:thisport%5D/ (which makes the new URL a URI) to force a external redirection. If no code is given a HTTP response of 302 (MOVED TEMPORARILY) is used. If you want to use other response codes in the range 300-400 just specify them as a number or use one of the following symbolic names: temp (default), permanent, seeother. Use it for rules which should canonicalize the URL and give it back to the client, e.g., translate “/~” into “/u/” or always append a slash to /u/user, etc.Note: When you use this flag, make sure that the substitution field is a valid URL! If not, you are redirecting to an invalid location! And remember that this flag itself only prefixes the URL with http://thishost%5B:thisport%5D/, rewriting continues. Usually you also want to stop and do the redirection immediately. To stop the rewriting you also have to provide the ‘L’ flag.
F Forbidden (sends 403 header) This forces the current URL to be forbidden, i.e., it immediately sends back a HTTP response of 403 (FORBIDDEN). Use this flag in conjunction with appropriate RewriteConds to conditionally block some URLs.
G Gone (no longer exists) This forces the current URL to be gone, i.e., it immediately sends back a HTTP response of 410 (GONE). Use this flag to mark pages which no longer exist as gone.
P Proxy This flag forces the substitution part to be internally forced as a proxy request and immediately (i.e., rewriting rule processing stops here) put through the proxy module. You have to make sure that the substitution string is a valid URI (e.g., typically starting with http://hostname) which can be handled by the Apache proxy module. If not you get an error from the proxy module. Use this flag to achieve a more powerful implementation of the ProxyPass directive, to map some remote stuff into the namespace of the local server.Notice: To use this functionality make sure you have the proxy module compiled into your Apache server program. If you don’t know please check whether mod_proxy.c is part of the “httpd -l” output. If yes, this functionality is available to mod_rewrite. If not, then you first have to rebuild the “httpd” program with mod_proxy enabled.
L Last Rule Stop the rewriting process here and don’t apply any more rewriting rules. This corresponds to the Perl last command or the break command from the C language. Use this flag to prevent the currently rewritten URL from being rewritten further by following rules. For example, use it to rewrite the root-path URL (‘/’) to a real one, e.g., ‘/e/www/’.
N Next (i.e. restart rules) Re-run the rewriting process (starting again with the first rewriting rule). Here the URL to match is again not the original URL but the URL from the last rewriting rule. This corresponds to the Perl next command or the continue command from the C language. Use this flag to restart the rewriting process, i.e., to immediately go to the top of the loop.But be careful not to create an infinite loop!
C Chain This flag chains the current rule with the next rule (which itself can be chained with the following rule, etc.). This has the following effect: if a rule matches, then processing continues as usual, i.e., the flag has no effect. If the rule does not match, then all following chained rules are skipped. For instance, use it to remove the “.www” part inside a per-directory rule set when you let an external redirect happen (where the “.www” part should not to occur!).
T=mime-type Set Mime Type Force the MIME-type of the target file to be MIME-type. For instance, this can be used to simulate the mod_alias directive ScriptAlias which internally forces all files inside the mapped directory to have a MIME type of “application/x-httpd-cgi”.
NS Skip if internal sub-request This flag forces the rewriting engine to skip a rewriting rule if the current request is an internal sub-request. For instance, sub-requests occur internally in Apache when mod_include tries to find out information about possible directory default files (index.xxx). On sub-requests it is not always useful and even sometimes causes a failure to if the complete set of rules are applied. Use this flag to exclude some rules.Use the following rule for your decision: whenever you prefix some URLs with CGI-scripts to force them to be processed by the CGI-script, the chance is high that you will run into problems (or even overhead) on sub-requests. In these cases, use this flag.
NC Case insensitive This makes the Pattern case-insensitive, i.e., there is no difference between ‘A-Z’ and ‘a-z’ when Pattern is matched against the current URL.
QSA Append query string This flag forces the rewriting engine to append a query string part in the substitution string to the existing one instead of replacing it. Use this when you want to add more data to the query string via a rewrite rule.
NE Do not escape output This flag keeps mod_rewrite from applying the usual URI escaping rules to the result of a rewrite. Ordinarily, special characters (such as ‘%’, ‘$’, ‘;’, and so on) will be escaped into their hexcode equivalents (‘%25’, ‘%24’, and ‘%3B’, respectively); this flag prevents this from being done. This allows percent symbols to appear in the output, as inRewriteRule /foo/(.*) /bar?arg=P1\%3d$1 [R,NE]

which would turn ‘/foo/zed’ into a safe request for ‘/bar?arg=P1=zed’.

PT Pass through This flag forces the rewriting engine to set the uri field of the internal request_rec structure to the value of the filename field. This flag is just a hack to be able to post-process the output of RewriteRule directives by Alias, ScriptAlias, Redirect, etc. directives from other URI-to-filename translators. A trivial example to show the semantics: If you want to rewrite /abc to /def via the rewriting engine of mod_rewrite and then /def to /ghi with mod_alias:RewriteRule ^/abc(.*) /def$1 [PT]
Alias /def /ghi

If you omit the PT flag then mod_rewrite will do its job fine, i.e., it rewrites uri=/abc/… to filename=/def/… as a full API-compliant URI-to-filename translator should do. Then mod_alias comes and tries to do a URI-to-filename transition which will not work.

Note: You have to use this flag if you want to intermix directives of different modules which contain URL-to-filename translators. The typical example is the use of mod_alias and mod_rewrite..

S=x Skip next x rules This flag forces the rewriting engine to skip the next num rules in sequence when the current rule matches. Use this to make pseudo if-then-else constructs: The last rule of the then-clause becomes skip=N where N is the number of rules in the else-clause. (This is not the same as the ‘chain|C’ flag!)
E=var:value Set environment variable “var” to “value” This forces an environment variable named VAR to be set to the value VAL, where VAL can contain regexp backreferences $N and %N which will be expanded. You can use this flag more than once to set more than one variable. The variables can be later dereferenced in many situations, but usually from within XSSI (via ) or CGI (e.g. $ENV{‘VAR’}). Additionally you can dereference it in a following RewriteCond pattern via %{ENV:VAR}. Use this to strip but remember information from URLs.

RewriteCond FLAGS

NC Case insensitive
OR Allows a rule to apply if one of a series of conditions are true.

Redirection Header Codes

301 Moved permanently
302 Moved temporarily
403 Forbidden
404 Not found
410 Gone

Server Variables

Format
%{NAME_OF_VAR}
HTTP Headers
HTTP_USER_AGENT
HTTP_REFERER
HTTP_COOKIE
HTTP_FORWARDED
HTTP_HOST
HTTP_PROXY_CONNECTION
HTTP_ACCEPT
Request
REMOTE_ADDR
REMOTE_HOST
REMOTE_USER
REMOTE_IDENT
REQUEST_METHOD
SCRIPT_FILENAME
PATH_INFO
QUERY_STRING
AUTH_TYPE
Server
DOCUMENT_ROOT
SERVER_ADMIN
SERVER_NAME
SERVER_ADDR
SERVER_PORT
SERVER_PROTOCOL
SERVER_SOFTWARE
Time
TIME_YEAR
TIME_MON
TIME_DAY
TIME_HOUR
TIME_MIN
TIME_SEC
TIME_WDAY
TIME
Special
API_VERSION
THE_REQUEST
REQUEST_URI
REQUEST_FILENAME
IS_SUBREQ

Directives

RewriteEngine
RewriteOptions
RewriteLog
RewriteLogLevel
RewriteLock
RewriteMap
RewriteBase
RewriteCond
RewriteRule

Apache Redirect

I recently ran into an expression in an httpd.conf file that got me to researching Redirect

The configuration directives tell Apache to get content from a specific place in the filesystem and return it to the client. Sometimes it is desirable, instead to inform the client that the requested content is located at a different URL, and instruct the client to make a new request with the new URL. This is called redirection and is implemented by the Redirect directive. For example, if the contents of the directory /foo under the DocumentRoot are moved to /bar, you can instruct clients to request the content at the new location as follows:

Redirect permanent /foo http://www.example.com/bar

This will redirect any URL-path starting in /foo to the same URL path on the http://www.example.com server with /bar substituted for /foo. You can redirect clients to any server, not only to the origin server.

Apache also provides a RedirectMatch directive for more complicated rewriting problems.  For example, to redirect requests for the site home page to a different site, but leave all other requests alone, use the following:

RedirectMatch permanent ^/$ http://www.example.com/startpage.html

Alternatively, to temporarily redirect all pages on one site to a particular page on another site, use the following:

RedirectMatch temp .* http://othersite.example.com/startpage.html

I also notice an interesting character in one of my Redirect statements

RedirectMatch (?i)\/foo http://www.example.com/bar/

The RedirectMatch uses regular expressions. The (?i) stands for case insensitive so the above expression would match /foo /Foo /FOo /FOO /fOO etc.

Apache .htaccess error message

Permission denied: /home/dsweeney/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable

I have seen several posts describing how to resolve this error message. Most of them are mentioning an images directory. I have run into this issue as a sys admin where I allow user directories to be web accessible.  The public_html directory in a users home directory is where users can put docs they want to view via a browser.

Well the solution is to check the permissions of the directories in the entire path of the public_html folder. If the permissions for /home are 700 you will get the above error message.  If /home/username is 700 same thing and all the way down.

Solution: chmod 755 the directory with the incorrect permissions.  I have found for this particular scenario it’s the /home/username directory.

Shibboleth Apache Multiple Virtual Host configuration for Moodle

About

Below are steps to configure a shibboleth SP to work with multiple Apache virtual hosts using a single entityID and an Assertion Consumer Service (ACS) and shibboleth’s NativeSPApplicationOverride. More information can be found here regarding NativeSPApplicationOverride

You will need to do this if you are running more than one virtual named host and each virtual host is running it’s own Moodle instance.

In this example, we will use the server names http://www.moodle1.ucla.edu andhttp://www.moodle2.ucla.edu with an entityID of http://www.moodle1.ucla.edu.

Note: You will need shibboleth installed and 2 instances of Moodle installed. You will also have needed to request attribute releases for the entityID and the ACS wherehttp://www.moodle1.ucla.edu is the entityID and http://www.moodle2.ucla.edu is the ACS that is associated with the http://www.moodle1.ucla.edu entityID.

shibboleth2.xml file configuration

Below are the changes I needed to make in the default configuration file. All other settings were left as default from the shibboleth 2.1 installation.

Modifying the host name for the 2 virtual host web servers

<RequestMapper type="Native"><RequestMap applicationId="default">

<Host name="www.moodle1.ucla.edu" ><Path name="default" authType="shibboleth" requireSession="true"/></Host>

<Host name="www.moodle2.ucla.edu" applicationId="moodle2" authType="shibboleth" requireSession="true"/>

</RequestMap></RequestMapper>

Entering entityID

<ApplicationDefaults id="default" policyId="default"entityID="http://www.moodle1.ucla.edu"REMOTE_USER="Shib-eduPersonPrincipalName"signing="false" encryption="false">

Point to Production UCLA IdP

<SessionInitiator type="Chaining" Location="/Login" isDefault="true" id="default"relayState="cookie" entityID="urn:mace:incommon:ucla.edu">

Pulling the MetadataProvider ID Information

<MetadataProvider id="incommon" type="XML"xmlns="urn:mace:shibboleth:2.0:metadata"url="http://wayf.incommonfederation.org/InCommon/InCommon-metadata.xml"backingFilePath="/etc/shibboleth/InCommon-metadata.xml"reloadInterval="28800"></MetadataProvider>

Setup the ApplicationOverride

<ApplicationOverride id="moodle2" entityID="http://www.moodle1.cdh.ucla.edu"/&gt;

Save and close the file. Check the shibboleth configuration file for errors: shibd -t and restart the shibboleth service: service shibd restart

Apache Virtual Host Configuration

Note: The Moodle root for www.moodle1.ucla.edu is at /var/www/html/moodle1 and the Moodle root for www.moodle2.ucla.edu is at /var/www/html/moodle2.

At the bottom of the httpd.conf file there should be a Virtual Hosts section. You will need to uncomment and add the following lines in your httpd.conf file.

Use name-based virtual hosting.NameVirtualHost *:80

<VirtualHost *:80>

ServerAdmin webmaster@ucla.edu

DocumentRoot /var/www/html/moodle1

ServerName www.moodle1.ucla.edu

This section allows for the use of .htaccess files to enable Shibboleth on directories

<Directory "/var/www/html/moodle1">

Options All

AllowOverride All

Order allow,deny

Allow from all

</Directory>

This section is required by Moodle to use Shibboleth authentication along with local authentication by only restricting the index.php file to shib auth.

<Directory /var/www/html/moodle1/auth/shibboleth/index.php>

AuthType shibboleth

ShibRequireSession On

require valid-user

</Directory>

</VirtualHost>

<VirtualHost *:80>

ServerAdmin webmaster@ucla.edu

DocumentRoot /var/www/html/moodle2

ServerName www.moodle2.ucla.edu

This section allows for the use of .htaccess files to enable Shibboleth on directories

<Directory "/var/www/html/moodle2">

Options All

AllowOverride All

Order allow,deny

Allow from all

</Directory>

This section is required by Moodle to use Shibboleth authentication along with local authentication by only restricting the index.php file to shib auth.

<Directory /var/www/html/moodle2/auth/shibboleth/index.php>

AuthType shibboleth

ShibRequireSession On

require valid-user

</Directory>

</VirtualHost>

Save and close the file and check the apache configuration: httpd -t Then restart apache. sudo /sbin/service httpd restart

Configure Moodle to use Shibboleth authentication and local login

For this to work you need to have the require shibboleth directives only restricting the index.php file in the auth/shibboleth/ directory. You can then put a link to auth/shibboleth/index.php page in the login page and should be able to login with both local and shibboleth accounts.

#1. As Moodle admin, under Site Administrator, browse to Users → Authentication → Shibboleth.

#2. Fill in the fields of the form. The fields ‘Username’, ‘First Name’, ‘Surname’, etc. should contain the name of the environment variables of the Shibboleth attributes that you want to map onto the corresponding Moodle variable. For Shibboleth 2.1, these are set in the attribute-map.xml file.

##################################################################### Shibboleth Attributes needed by Moodle: For Moodle to work properly Shibboleth should at least provide the attribute that is used as username in Moodle. It has to be unique for all Shibboleth Be aware that Moodle converts the username to lowercase. So, the overall behaviour of the username will be case-insensitive. All attributes used for moodle must obey a certain length, otherwise Moodle cuts off the ends. Consult the Moodle documentation for further information on the maximum lengths for each field in the user profile. #####################################################################

#3. Save the changes you made on the Shibboleth page.

#4. Browse to Users → Authentication → Manage Authentication to Enable and Disable Shibboleth login. You can control the priority of the failthrough here if you would like as well.

#5. Save the changes.

CCLE UCLAlogin.php page

If you are going to use CCLE UCLAlogin.php page you will need to edit the htpswwwroot variable and hard code the server name.

Example for www.moodle1.ucla.edu Comment this line://$CFG->httpswwwroot = str_replace("http://", "https://", $CFG-httpswwwroot);Enter this instead:$CFG->httpswwwroot ="http://www.moodle1.ucla.edu";