Apache Web server Configuration - Yash-777/SteamingServlet GitHub Wiki

WebServer

A web server is software that listens for requests and returns data (usually a file). When you type “www.mysite.com”, the request is forwarded to a machine running web server software which returns a file back to your browser, e.g. the contents of index.html. The browser might then make further requests based on the HTML content, e.g. CSS, JavaScript, and graphic files.

Since the web server sits between your browser and the requested file, it can perform processing that is not possible by opening an HTML file directly. For example, it can parse PHP code which connects to a database and returns data.

You can use your host’s web server for testing, but uploading will become tiresome and changes could go live before they had been fully tested. What you need is a local web server installation.

How to install & configure Apache on a Windows server

Tomcat Application Server:

  • Redirection can be done form the application
  • Single App Server domian/app
  • Static Files and Applications
    • D:\Yash\Apache Server\apache-tomcat-8.0.32\webapps\ROOT\tomcat.gif
    • http://localhost:8080/tomcat.gif

Apache Web Server: Apache Lounge 2.4.41

  • Redirection can be done form the server
  • Can Navigate to Multiple App Servers domain/tomcat1/app, domain/tomcat2/app
  • Only Static files
    • D:\Yash\Apache Server\httpd-2.4.41-win64-VS16\Apache24\htdocs\index.html
    • http://localhost:80/index.html

Redirect Directive Redirect [status] [URL-path] URL

The Redirect directives are used to instruct clients to make a new request with a different URL. They are often used when a resource has moved to a new location.

Then any request beginning with URL-path will return a redirect request to the client at the location of the target URL. Additional path information beyond the matched URL-path will be appended to the target URL.

#With Redirect
Redirect "/docs/" "http://new.example.com/docs/"

# Redirect to a URL on a different host
Redirect "/service" "http://foo2.example.com/service"

# Redirect to a URL on the same host
Redirect "/one" "/two"

# 
Redirect permanent "/one" "http://example.com/two"
Redirect 303 "/three" "http://example.com/other"

RedirectMatch Directive RedirectMatch [status] regex URL

# A request for http://www.example.com/avatar.jpg will be redirected to http://static.example.com/avatar.jpg
RedirectMatch (.*)\.jpg$ http://static.example.com$1.jpg

#With RedirectMatch
RedirectMatch "^/docs/(.*)" "http://new.example.com/docs/$1"
<VirtualHost *:80>
  ServerName undesired.example.com
  ServerAlias example.com notthis.example.com
  UseCanonicalName on

  Redirect "/" "http://www.example.com/"
</VirtualHost>
 
# REQUEST_METHOD, SERVER_PROTOCOL, HTTP_HOST, SERVER_PORT, REQUEST_URI, QUERY_STRING, HTTP_USER_AGENT
<If "%{HTTP_HOST} != 'www.example.com'">
    Redirect "/" "http://www.example.com/"
</If>

<If "%{SERVER_PROTOCOL} != 'HTTPS'">
    Redirect "/admin/" "https://www.example.com/admin/"
</If>

<If "%{REQUEST_URI} != 'HTTPS'">
    Redirect "/admin/" "https://www.example.com/admin/"
</If>

Variables The expression parser provides a number of variables of the form %{HTTP_HOST}. Note that the value of a variable may depend on the phase of the request processing in which it is evaluated.

REQUEST_METHOD    [GET/POST]
SERVER_PROTOCOL   [HTTP/HTTPS]
HTTP_HOST         [www.example.com]
SERVER_PORT       [80,443,8080]
REQUEST_URI       [The path part of the request's URI]
QUERY_STRING      [?x=a&y=b]
HTTP_USER_AGENT   ["^Mozilla/3.*"]

Apache Configuration for HTTPS Redirection

Example: Ensure mod_rewrite.so module is loaded

To configure the redirects, add the following redirect rule either to the Apache config file if you have access to it, or to the .htaccess in the root of your site:

LoadModule rewrite_module modules/mod_rewrite.so

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

All these tokens are joined together, and represents the final redirect URI. Finally, we append 3 flags:

  • NE to not escape special characters
  • R=301 to use the HTTP 301 redirect status
  • L to stop processing other rules, and redirect immediately

If the Redirect directive is used within a or section with the URL-path omitted, then the URL parameter will be interpreted using expression syntax.

This syntax is available in Apache 2.4.19 and later.

Redirect 303 "/three" "http://example.com/other"

<Location "/one">
    Redirect permanent "http://example.com/two"
</Location>
<Location "/three">
    Redirect 303 "http://example.com/other"
</Location>

Canonical Host names with Redirect Directive vhost examples

WebServer Location Base Loation: {ServerPath} = D:\Yash\Apache Server\httpd-2.4.41-win64-VS16\Apache24#

Step 1: Load Virtual hosts Configuration file from {ServerPath}/conf/httpd.conf file by Including it.

# Virtual hosts
#Include conf/extra/httpd-vhosts.conf # Default
Include conf/extra/httpd-vhosts.conf

Step 2: Add Redirection information in {ServerPath}/conf/extra/httpd-vhosts.conf

<VirtualHost *:80>
    ServerName localhost
    Redirect "/redirect" "http://localhost/redirection.html"
</VirtualHost>

# {ServerPath}\htdocs\app\index.html - app folder is created in htdocs
# Write - http://localhost/app/ « http://localhost:8080/tomcat.gif
# Wrong - http://localhost/app/INDEX.HTML « http://localhost:8080/tomcat.gifINDEX.HTML
<VirtualHost *:80>
    ServerName localhost
    Redirect "/app/" "http://localhost:8080/tomcat.gif"
</VirtualHost>

Step 3: Create Static file as {ServerPath}/htdocs/redirection.html. With following content WebServer/htdocs - same as - Tomcat/webapps/Root

<html><body>
  <h1>Please use CLOUD environment</h1>
</body></html>

# D:\Yash\Apache Server\apache-tomcat-8.0.32\webapps\ROOT\tomcat.gif
# http://localhost:8080/tomcat.gif

# * VirtualHost with IPv4, IPv6 - https://httpd.apache.org/docs/2.4/mod/core.html#servername
# * DocumentRoot must be a directory - https://httpd.apache.org/docs/trunk/vhosts/examples.html
# * # ServerName gives the name and port that the server uses to identify itself. [scheme://]domain-name|ip-address[:port]

# httpd.conf
# * Define SRVROOT "D:/Yash/Apache Server/httpd-2.4.41-win64-VS16/Apache24"
# * ServerRoot "${SRVROOT}"
# * DocumentRoot "${SRVROOT}/htdocs"
# * <Directory "${SRVROOT}/htdocs"> Require all granted </Directory>
# * ErrorLog "logs/error.log"
# * LogLevel warn
# * <IfModule log_config_module> CustomLog "logs/access.log" common </IfModule>
# * Virtual hosts - Include conf/extra/httpd-vhosts.conf - https://httpd.apache.org/docs/2.2/vhosts/details.html
<VirtualHost *:80>
    ServerName "localhost"
	
	# http://localhost/tomcat.gif « http://localhost:8080/tomcat.gif
	<If "%{REQUEST_URI} == '/tomcat.gif'">
		# Redirect "/" "http://localhost:8080/" # appends Above path here
		Redirect 303 "/tomcat.gif" "http://localhost:8080/tomcat.gif"
		
		<If "%{SERVER_PROTOCOL} == 'HTTP'">
			Redirect "/tomcat.gif" "http://localhost:8080/tomcat.gif_HttpS"
		</If>
	</If>

	# [Boolean expressions](https://httpd.apache.org/docs/2.4/sections.html#expressions)
    # The <If> directive change the configuration depending on a condition which can be expressed by a boolean expression. For example, 
	# the following configuration denies access if the HTTP Referer header does not start with "http://www.example.com/".
	<If "!(%{HTTP_REFERER} -strmatch 'http://www.example.com/*')">
		Require all denied
	</If>

	Redirect "/a" "http://localhost/redirection.html"
	Redirect "/yash.dev" "http://localhost/redirection.html"
	Redirect "/yash.qa" "http://localhost/redirection.html"
</VirtualHost>

# https://httpd.apache.org/docs/2.4/vhosts/name-based.html
# VirtualHost:: The first step is to create a <VirtualHost> block for each different host that you would like to serve.
# If same conf then The first VirtualHost section is used for all requests  # http://localhost/a - 404 [] ServerName "localhost" Redirect "/a" "http://localhost/redirection.html"

# DocumentRoot must be a directory
# Redirect takes one, two or three arguments, an optional status, then document to be redirected and destination URL
#<VirtualHost *:80>    ServerName "localhost"    Redirect "/yash" "http://localhost/redirection.html"  </VirtualHost>

# ServerName "localhost/redirect" Do not use any path name over here, 
# http://localhost/redirection.htmlredirection.htmlredirection.htmlredirection.html...redirect/
# logs/access.log
# ::1 - - [13/Dec/2019:14:17:23 +0100] "GET /yash/ HTTP/1.1" 302 222
# ::1 - - [13/Dec/2019:14:17:23 +0100] "GET /redirection.htmlyash/ HTTP/1.1" 302 238
# ::1 - - [13/Dec/2019:14:17:23 +0100] "GET /redirection.htmlredirection.htmlyash/ HTTP/1.1" 302 254
# ::1 - - [13/Dec/2019:14:17:23 +0100] "GET /redirection.htmlredirection.htmlredirection.htmlyash/ HTTP/1.1" 302 270

Sample Server Config File: https://gist.github.com/andydavies/6024703

ServerRoot "/webdienste/webservers/apache/yash.github.com-https/current"
PidFile logs/httpd.pid

CoreDumpDirectory logs/core-dumps

Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15

#Settings for MPM-prefork (PHP)
<IfModule prefork.c>
  ServerLimit          400
  StartServers         5
  MinSpareServers      5
  MaxSpareServers      15
  MaxClients           400 
  MaxRequestsPerChild  50000
</IfModule>

#Settings for MPM-worker (non-PHP)
<IfModule worker.c>
 # ServerLimit is per default 16 and has to be increased if MaxClient is increased ( MC = TPC * SL )
 StartServers         3
 MaxClients           400
 MinSpareThreads      25
 MaxSpareThreads      75
 MaxRequestsPerChild  50000
</IfModule>

#Listen 10.253.39.55:80
Listen 10.253.39.55:443

ExtendedStatus On

User nobody
Group nogroup

ServerAdmin [email protected]

UseCanonicalName Off


# In case of certificate authentification, remove comment:
#LoadModule auth_certificate_module modules/mod_auth_certificate.so

#Only for request debugging
#ForensicLog logs/forensic.log

DocumentRoot "/webdienste/content/Account/yash.github.com-https/htdocs"
Alias /webhosting /webdienste/content/eis/optw_docs
Alias /lbmonitor /webdienste/webservers/apache/yash.github.com-https/2.4.28/monitoring/lbmonitor

<Directory />
    Options none 
    AllowOverride None
    Order Deny,Allow
    Deny from all
</Directory>

<Directory "/webdienste/content/eis/optw_docs">
    Options none 
    AllowOverride None
    Order allow,deny
    Allow from 127.0.10.1/27
    Allow from 10.19.31.11
    Allow from 10.19.31.12
    Allow from 10.19.31.13
</Directory>

<Directory "/webdienste/content/eis/optw_docs/testseite">
   Options none
   AllowOverride None
   Order deny,allow
   Deny from All
   <Files "index.php">
       Options none
       Order deny,allow
       Allow from All
   </Files>
</Directory>

<Directory "/webdienste/webservers/apache/yash.github.com-https/2.4.28/monitoring/lbmonitor">
    Options none 
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>


<Directory "/webdienste/content/Account/yash.github.com-https/htdocs">
    Options none 
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

DirectoryIndex index.html index.htm index.php index.phtml

AccessFileName .htaccess

# Exclude .ht(access,passwd,etc,pp)
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
</Files>

# Exclude some file extensions
<Files ~ "^.*\.(inc|include|ini|swp|bak|conf|cnf)$">
    Order allow,deny
    Deny from all
</Files>

# Exclude backup files from e.g. vim
<Files ~ "^.*\~$">
    Order allow,deny
    Deny from all
</Files>

# Hide SCM Directories
RedirectMatch 404 (.*)?/\.svn(/.*|$)
RedirectMatch 404 (.*)?/\.git(/.*|$)
RedirectMatch 404 (.*)?/\.cvs(/.*|$)
RedirectMatch 404 (.*)?/CVS(/.*|$)

TypesConfig conf/mime.types

HostnameLookups Off

CookieName SessionID
CookieTracking on

LogLevel warn
SetEnvIf Remote_Addr "127.0.0.1" dontlog 
LogFormat "\"%{X-Forwarded-For}i\" %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\" \"%{cookie}n\" %D" common 

ServerTokens productonly
ServerSignature Off

AddLanguage de .de
AddLanguage en .en

AddCharset ISO-8859-1  .iso8859-1  .latin1
AddCharset UTF-8       .utf8
AddCharset utf-8       .utf8

AddType application/x-tar .tgz
AddEncoding x-compress .Z
AddEncoding x-gzip .gz .tgz
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddType video/x-ms-asf .asf .asx
AddType audio/x-ms-wma .wma
AddType audio/x-ms-wax .wax
AddType video/x-ms-wmv .wmv
AddType video/x-ms-wvx .wvx
AddType video/x-ms-wm .wm
AddType video/x-ms-wmx .wmx
AddType application/x-ms-wmz .wmz
AddType application/x-ms-wmd .wmd
AddType application/msword .doc .dot
AddType application/vnd.ms-excel .xls .xla .xlt
AddType application/ms-powerpoint .ppt .pps .ppa .pot
AddType application/ms-outlook .oft .msg
AddType application/onenote  .onetoc .onetoc2 .onetmp .onepkg
AddType application/vnd.ms-word.document.macroEnabled.12 .docm
AddType application/vnd.openxmlformats-officedocument.wordprocessingml.document .docx
AddType application/vnd.openxmlformats-officedocument.wordprocessingml.template .dotx
AddType application/vnd.ms-powerpoint.template.macroEnabled.12 .potm
AddType application/vnd.openxmlformats-officedocument.presentationml.template .potx
AddType application/vnd.ms-powerpoint.addin.macroEnabled.12 .ppam
AddType application/vnd.ms-powerpoint.slideshow.macroEnabled.12 .ppsm
AddType application/vnd.openxmlformats-officedocument.presentationml.slideshow .ppsx
AddType application/vnd.ms-powerpoint.presentation.macroEnabled.12 .pptm
AddType application/vnd.openxmlformats-officedocument.presentationml.presentation .pptx
AddType application/vnd.ms-excel.addin.macroEnabled.12     .xlam
AddType application/vnd.ms-excel.sheet.binary.macroEnabled.12 .xlsb
AddType application/vnd.ms-excel.sheet.macroEnabled.12     .xlsm
AddType application/vnd.openxmlformats-officedocument.spreadsheetml.sheet .xlsx
AddType application/vnd.ms-excel.template.macroEnabled.12  .xltm
AddType application/vnd.openxmlformats-officedocument.spreadsheetml.template .xltx
AddType application/vnd.ms-excel.template.macroEnabled.12  .xltm
AddType application/vnd.ms-word.template.macroEnabled.12   .dotm


BrowserMatch "Mozilla/2" nokeepalive
BrowserMatch ".*MSIE.*" ssl-unclean-shutdown 
BrowserMatch "RealPlayer 4\.0" force-response-1.0
BrowserMatch "Java/1\.0" force-response-1.0
BrowserMatch "JDK/1\.0" force-response-1.0
BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully
BrowserMatch "^WebDrive" redirect-carefully
BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully
BrowserMatch "^gnome-vfs" redirect-carefully

# Repeat below Location Directive for paths /server-info, /ldap-status
<Location /server-status> # /ldap-status
    SetHandler server-status # SetHandler ldap-status 
    RewriteEngine off
    Order deny,allow
    Deny from all
    Allow from 127.0.10.1/27
    Allow from 127.0.0.1
</Location>


# If you build a reverse-proxy to an IIS Server, use this rewrite-rule:
#RewriteEngine on 
#RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK) 
#RewriteRule .* - [F] 
# If there are only Apache Servers, this option is sufficient:
TraceEnable Off

# Drop the Range header when more than 5 ranges. DO NOT REMOVE IN HTTPD < 2.2.20!
# CVE-2011-3192
SetEnvIf Range (,.*?){5,} bad-range=1
RequestHeader unset Range env=bad-range


SSLPassPhraseDialog  builtin
SSLSessionCache shmcb:/webdienste/webservers/apache/yash.github.com-https/current/logs/sslcache(512000)
SSLSessionCacheTimeout 300
SSLRandomSeed startup file:/dev/urandom 1024
SSLRandomSeed connect file:/dev/urandom 1024

# Disable vulnerable protocols.
SSLProtocol all -SSLv2 -SSLv3

SSLHonorCipherOrder on
# Default - no RC4, 3DES allowed because ot Netcool ISM
SSLCipherSuite "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EECDH EDH+aRSA 3DES-EDE-CBC-SHA RC4 !aNULL !eNULL !LOW !MD5 !EXP !PSK !SRP !DSS !RC4"

# In case of authentification, remove comments:
# LDAPVerifyServerCert Off
# AuthLDAPCharsetConfig conf/charset.conv


## Activate only when Port 80 _AND_ 443 were ordered by the customer !
## Rewrite from http:// to https://
#<VirtualHost 127.0.0.1:80>
#     ServerName yash.github.com
#     RewriteEngine on
#     RewriteRule .* - [F]
#     RewriteRule ^/$ https://yash.github.com/ [R]
#</VirtualHost>

# VirtualHost without ClientCert auth
<VirtualHost 127.0.01:443>
   ServerName yash.github.com

   SSLEngine On
   SSLCertificateFile /conf/cert/MY_SSL_CERT.crt
   SSLCertificateKeyFile /conf/cert/MY_SSL_CERT.key
   # Please use the correct one for your Certificate - https://wiki.intranet.eon-is.com/eis-ts1a/doku.php?id=ca-bundles
   SSLCertificateChainFile /conf/cert/MY_CERT-v1.crt
   SSLOptions +StdEnvVars +OptRenegotiate +ExportCertData

   # Use ForensicLog only for debugging
   # ForensicLog logs/yash.github.com-https_forensic_log
   ErrorLog logs/Tomcat-https_error_log
   CustomLog logs/Tomcat-https_access_log common env=!dontlog
 
   # Exceptions in request forwarding to Tomcat, DO NOT REMOVE!
   ProxyPassMatch /server-status !
   ProxyPassMatch /server-info !
   ProxyPassMatch /ldap-status !
   ProxyPassMatch /lbmonitor !
   ProxyPassMatch /webhosting !

   # Passing all the requests to Tomcat, please only pass the application's location.
   ProxyPass / ajp://10.16.166.236:11001/ keepalive=On timeout=30 connectiontimeout=30 retry=20
   ProxyPassReverse / ajp://10.16.166.236:11001/

   #AJP#
   Redirect "/yash.dev" "http://localhost/redirection.html"
   
   # http://localhost/tomcat.gif « http://localhost:8080/tomcat.gif
   <If "%{REQUEST_URI} == '/tomcat.gif'">
      # Redirect "/" "http://localhost:8080/" # appends Above path here
      Redirect 303 "/tomcat.gif" "http://localhost:8080/tomcat.gif"
   </If>

   # Tomcat balancing example with mod_proxy_balancer
   # The node1 and node2 descriptions have to be added als jvmRoute="nodeX" to the "Engine" setting in server.xml on the Tomcats
   #<Proxy balancer://pool>
   # BalancerMember ajp://<TOMCAT-HOST>:<TOMCAT-PORT> route=node1
   # BalancerMember ajp://<TOMCAT-HOST>:<TOMCAT-PORT> route=node2
   #</Proxy>
   #ProxyPass / balancer://pool/ stickysession=JSESSIONID
   #ProxyPassReverse / balancer://pool/
  
   # Restrict access to Tomcat admin, manager and probe applications to administrators
   <Location /manager>
     Order deny,allow
     deny from all
     Allow from 127.0.0.1/27
   </Location>

  ## Example for ReverseProxy
  #
  # Rewrite requests for / from local server to lbmonitor
  # This is required only if / is forwarded by proxypass, so the web server stats could work
  #RewriteEngine on
  #RewriteCond expr "-R '127.0.0.1'"
  #RewriteRule ^/$ /lbmonitor/active.html [PT]
  #
  #<Location /xxx>
  #    ProxyPass http://xxx keepalive=On retry=20 timeout=120
  #    ProxyPassReverse http://xxx
  #    RewriteEngine on
  #    RewriteCond %{REMOTE_USER} (.*)
  #    RewriteRule .* - [E=USER:%1]
  #    RequestHeader set "HTTP_USER_ID" "%{USER}e"
  #    RequestHeader set "CLIENTPROTOCOL" "https"
  #    Header unset Vary
  #    # DO NOT REMOVE THE FOLLOWING LINES
  #    ProxyPassMatch /server-status !
  #    ProxyPassMatch /server-info !
  #    ProxyPassMatch /ldap-status !
  #    ProxyPassMatch /lbmonitor !
  #    ProxyPassMatch /webhosting !
  #    # If you prefer to use RewriteRules for reverse proxies
  #    #RewriteCond %{REQUEST_URI} !/server-status
  #    #RewriteCond %{REQUEST_URI} !/server-info
  #    #RewriteCond %{REQUEST_URI} !/ldap-status
  #    #RewriteCond %{REQUEST_URI} !/lbmonitor
  #    #RewriteCond %{REQUEST_URI} !/webhosting.*
  #</Location>
</VirtualHost>
⚠️ **GitHub.com Fallback** ⚠️