# How do I redirect subdomains to a different port on the same server?

In Apache, you can redirect requests from subdomains to a different port on the same server using VirtualHost configurations and mod_proxy. This allows you to redirect traffic from a subdomain to a specific port, effectively serving content from that port while using the subdomain as an access point. Here's a guide to accomplish this:

### Prerequisites:

- Ensure that `mod_proxy` and `mod_proxy_http` are enabled:
    
    ```bash
    sudo a2enmod proxy
    sudo a2enmod proxy_http
    sudo systemctl restart apache2
    
    ```
    

### Steps to Redirect Subdomains to a Different Port:

1. Set Up Proxy Pass for the Subdomain:
Edit your Apache configuration file to define a VirtualHost for the subdomain and use the `ProxyPass` directive to redirect requests to a different port.
    
    ```
    <VirtualHost *:80>
        ServerName subdomain.example.com
        ProxyPass / <http://localhost:8080/>
        ProxyPassReverse / <http://localhost:8080/>
    </VirtualHost>
    
    ```
    
    - Replace `subdomain.example.com` with your subdomain.
    - `ProxyPass` and `ProxyPassReverse` direct requests to `localhost:8080` where the server on that port is expected to handle the traffic.
2. Update Configuration and Restart Apache:
Save your changes and restart Apache for the new configuration to take effect:
    
    ```bash
    sudo systemctl restart apache2
    
    ```
    

### Explanation:

- The `ProxyPass` directive forwards the incoming requests from the specified subdomain (`subdomain.example.com`) to the defined address and port (`http://localhost:8080/`).
- `ProxyPassReverse` ensures that the responses from the proxied server are rewritten to match the subdomain path, adjusting URLs in the response headers.

### Additional Notes:

1. Port Usage: Ensure the port you're redirecting to (`8080` in the example) is open and hosting the expected content.
2. SSL Configuration: For HTTPS redirection, include SSL configurations in the VirtualHost block and use `ProxyPass / <https://localhost:8080/`> for secure proxying.
3. Firewall Configuration: If you have a firewall enabled, ensure that the specified port is open for incoming connections.

With this configuration, Apache acts as a reverse proxy, redirecting incoming requests from the defined subdomain to a specific port on the same server, allowing you to host different services or applications on distinct ports and access them through subdomains. Adjust the configurations as per your server setup and application requirements.