Search code examples
wordpressapachehttp-redirectmod-rewrite

How to redirect one URL to a different directory (outside of DOCKER) using apache2


I have example.com which is an wordpress site installed inside docker, and I also have CI project stored in /var/www/store. I want user to be redirected to /var/www/store (outside docker) when entering example.com/store in address bar. This is my attempt.

<VirtualHost *:80>
  ServerName example.com
  Redirect permanent / https://example.com/
</VirtualHost>

<VirtualHost *:443>
  RequestHeader set "X-Forwarded-Proto" expr=%{REQUEST_SCHEME}
  RequestHeader set "X-Forwarded-SSL" expr=%{HTTPS}
  ServerAdmin kontak@japati.net
  ServerName example.com
  ProxyRequests Off

  <Location />
    ProxyPreserveHost On
    ProxyPass http://127.0.0.1:8100/
    ProxyPassReverse http://127.0.0.1:8100/
  </Location>
  
  RewriteEngine On
  RewriteRule ^/store(.*)$ /var/www/store$1 [L]

  SSLEngine on
  SSLCertificateFile /opt/acme-cert/example.com/cert.pem
  SSLCertificateKeyFile /opt/acme-cert/example.com/site.key
  SSLCertificateChainFile /opt/acme-cert/example.com/fullchain.cer

  ErrorLog ${APACHE_LOG_DIR}/error.log
  CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

But this doesn't work, I get page not found error from wordpress. I also tried alias /store /var/www/store but it still doesn't work.


Solution

  • Your problem is that you're trying to mix Docker with Apache, but right now ALL requests are getting forwarded to port 8100, which means obviously RewriteRules aren't going to help. (They'll get forwarded too.) (Anyways, you can't use RewriteRule to go to a physical location, only to a URL.)

    Your block is forwarding ALL requests to port 8100. Let's fix that:

    You'll want to add this:

    <VirtualHost *:443>
    
      #.......Stuff.......
      Alias /store "/var/www/store" #<---------------- map "/store" to /var/www/store
      ProxyPass /store ! #<-------------- Place this before any other ProxyPass declarations
      <Location />
        ProxyPreserveHost On
        ProxyPass http://127.0.0.1:8100/
        ProxyPassReverse http://127.0.0.1:8100/
      </Location>
    

    Or you could instead do this:

      #.......Stuff.......
      Alias /store "/var/www/store" #<---------------- map "/store" to /var/www/store
      <Location /store>
        ProxyPass !
      </Location>
      <Location />
        ProxyPreserveHost On
        ProxyPass http://127.0.0.1:8100/
        ProxyPassReverse http://127.0.0.1:8100/
      </Location>