Problems mod_rewrite

Posted on 2012-09-18
Last Modified: 2012-10-22
Hi experts,
we have created a rewrite-rule with mod_rewrite on an apache based webserver. The rule should rewrite every request without "www" to a request with "www". ->

Our rule works fine, but when a request uses HTTPS without the "www", the request is changed to with "www" but on HTTP. Is there a way to hold the protocol?

Our rules looks like this:
RewriteEngine on

RewriteCond %{HTTPS} (on)?
RewriteCond %{HTTP:Host} ^(?!www\.)(.+)$ [NC]
RewriteCond %{REQUEST_URI} (.+)
RewriteCond %{HTTP:Host} ^(testpage\.com)$ [NC]
RewriteRule .? http(?%1s)://www.%2%3 [R=301,L]

Best regards,
Question by:Systemadministration
    LVL 51

    Expert Comment

    RewriteCond %{SERVER_NAME} ^!www\.
    RewriteRule .* %{REQUEST_SCHEME}://

    Author Comment

    OK, but this works only for the root. ->

    But the rule must work for subdirs and all other requests: ->

    But there must be an exemption like this:
    RewriteCond %{HTTP:Host} ^(testpage\.com)$ [NC]

    Because without this condition, requests with localhost or the ip-adresse also gets rewritten to www.localhost or www.ip .

    Best regards,
    LVL 51

    Accepted Solution

    # add your exception as you need, then
    RewriteRule (.*) %{REQUEST_SCHEME}://$1[QSA]

    Featured Post

    Find Ransomware Secrets With All-Source Analysis

    Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

    Join & Write a Comment

    Introduction This article explores the design of a cache system that can improve the performance of a web site or web application.  The assumption is that the web site has many more “read” operations than “write” operations (this is commonly the ca…
    Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
    Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
    This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

    733 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now