Search code examples
apacheconfigurationdnssubdomainsubdirectory

Apache subdirectory redirect to subdomain


I'm facing an issue with Apache web server configuration. I have successfully configured a subdomain, https://subdomain.example.cloud/, which points to the content in a specific subdirectory, https://example.cloud/subdirectory1/subdirectory2/. However, I want to redirect direct access to https://example.cloud/subdirectory1/subdirectory2/ to the subdomain https://subdomain.example.cloud/, in order to prevent direct access to the files in the subdirectory. I've tried configuring Apache using VirtualHost and ProxyPass directives, but neither approach seems to be working as expected. The subdirectory is still accessible directly, and the redirection is not working. I've also attempted to set up access control within the VirtualHost configuration to deny access to the subdirectory, but that doesn't seem to be taking effect either. I'm seeking assistance in properly configuring Apache to achieve the desired redirection and access control. Any guidance or suggestions would be greatly appreciated.


Solution

  • Create an .htaccess file in your root directory and add a 301 redirect to it.

    Redirect 301 subdirectory2/ https://subdomain.example.cloud/
    

    Also you will need to make sure Apache rewrites are enabled

    sudo a2enmod rewrite
    
    sudo service apache2 restart
    

    Reading about .htaccess MIght be worth your while as well.

    Since you are using node.js

    This is an example of how I include a custom htaccess for my project during build time. I have a .htaccess file that sits 1 directory up from the src and I create a softlink to it during build time. In the "scripts" section of your package.json. Granted this is for my react apps . But it's all node, so you should be able glean the point I am trying to make.

    "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build && ln -s ../.htaccess build/.htaccess",
        "test": "react-scripts test",
        "eject": "react-scripts eject",
        "install:clean": "rm -rf node_modules/ && rm -rf package-lock.json && npm install && npm start"
      },