Creating a website preview application on your WordPress site hosts.dev involves both front-end and back-end development. Below is a comprehensive guide that walks you through building this functionality using the Code Snippets plugin for your back-end logic and WordPress shortcodes for the front-end interface.
Overview
-
Front-End:
- Form Creation: A user-facing form where clients can input their domain and IP address.
- Shortcode: Embedding the form using a WordPress shortcode.
-
Back-End:
- Handling Form Submission: Processing the input, generating a unique code, and storing the mapping between the code, domain, and IP.
- Redirect Mechanism: Handling URLs like
hosts.dev/g89gjd to redirect to givenomainacom.hosts.dev.
-
Database Management:
- Custom Post Type: Utilizing WordPress's custom post types to store the mappings.
-
Security Considerations:
- Input Sanitization: Ensuring all user inputs are sanitized to prevent security vulnerabilities.
Let's dive into each part step-by-step.
1. Front-End Development
a. Creating the Submission Form
We'll create a form where clients can enter their domain and IP address. This form will be embedded into any WordPress page using a shortcode.
Code Snippet for the Form Shortcode
-
Add a New Snippet in Code Snippets:
- Navigate to WordPress Dashboard → Code Snippets → Add New.
- Title it something like "Preview App Form and Processing".
-
Insert the Following Code:
// Shortcode to display the preview form
function preview_app_form_shortcode() {
// Check if the user is processing the form
if ( isset($_POST['preview_app_submit']) ) {
return preview_app_handle_form_submission();
}
// HTML form
$form = '
<form method="post" action="">
<label for="domain">Domain:</label><br>
<input type="text" id="domain" name="domain" required placeholder="e.g., example.com"><br><br>
<label for="ip">IP Address:</label><br>
<input type="text" id="ip" name="ip" required placeholder="e.g., 192.168.1.1"><br><br>
<input type="submit" name="preview_app_submit" value="Generate Preview URL">
</form>
';
return $form;
}
add_shortcode('preview_app_form', 'preview_app_form_shortcode');
// Function to handle form submission
function preview_app_handle_form_submission() {
// Check and sanitize inputs
$domain = isset($_POST['domain']) ? sanitize_text_field($_POST['domain']) : '';
$ip = isset($_POST['ip']) ? sanitize_text_field($_POST['ip']) : '';
if ( empty($domain) || empty($ip) ) {
return '<p>Please provide both domain and IP address.</p>';
}
// Validate domain
if ( !preg_match('/^(?!:\/\/)([a-zA-Z0-9-_]+\.)+[a-zA-Z]{2,11}?$/', $domain) ) {
return '<p>Invalid domain format.</p>';
}
// Validate IP
if ( !filter_var($ip, FILTER_VALIDATE_IP) ) {
return '<p>Invalid IP address.</p>';
}
// Generate unique code
$unique_code = generate_unique_code();
// Store the mapping
$post_id = wp_insert_post( array(
'post_title' => $unique_code,
'post_type' => 'preview',
'post_status' => 'publish',
));
if ( is_wp_error($post_id) ) {
return '<p>There was an error generating the preview URL. Please try again.</p>';
}
// Add meta data
add_post_meta($post_id, 'domain', $domain, true);
add_post_meta($post_id, 'ip', $ip, true);
// Construct the preview URL
$preview_url = home_url("/" . $unique_code);
return '<p>Your preview URL: <a href="' . esc_url($preview_url) . '">' . esc_html($preview_url) . '</a></p>';
}
// Function to generate a unique alphanumeric code
function generate_unique_code($length = 6) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$characters_length = strlen($characters);
$random_code = '';
for ($i = 0; $i < $length; $i++) {
$random_code .= $characters[rand(0, $characters_length - 1)];
}
// Ensure the code is unique
$existing = get_posts( array(
'post_type' => 'preview',
'title' => $random_code,
'numberposts' => 1,
));
if ( $existing ) {
// Recursive call if code exists
return generate_unique_code($length);
}
return $random_code;
}
// Register custom post type 'preview'
function register_preview_post_type() {
$labels = array(
'name' => 'Previews',
'singular_name' => 'Preview',
'menu_name' => 'Previews',
'name_admin_bar' => 'Preview',
'add_new' => 'Add New',
'add_new_item' => 'Add New Preview',
'new_item' => 'New Preview',
'edit_item' => 'Edit Preview',
'view_item' => 'View Preview',
'all_items' => 'All Previews',
'search_items' => 'Search Previews',
'not_found' => 'No previews found.',
'not_found_in_trash' => 'No previews found in Trash.',
);
$args = array(
'labels' => $labels,
'public' => false,
'publicly_queryable' => true,
'show_ui' => false,
'show_in_menu' => false,
'query_var' => true,
'rewrite' => array( 'slug' => '', 'with_front' => false ), // Root-level
'capability_type' => 'post',
'has_archive' => false,
'hierarchical' => false,
'supports' => array( 'title' ),
);
register_post_type('preview', $args);
}
add_action('init', 'register_preview_post_type');
-
Explanation of the Code:
-
Shortcode [preview_app_form]: When you add [preview_app_form] to any WordPress page or post, it will render the submission form.
-
Form Handling:
- Validates and sanitizes user input for domain and IP.
- Generates a unique 6-character alphanumeric code.
- Stores the mapping as a custom post of type
preview with metadata for domain and IP.
- Displays the generated preview URL to the user.
-
Custom Post Type preview:
- Created to store each preview mapping.
- Publicly queryable to handle redirects.
- Does not have a UI in the WordPress admin sidebar to prevent clutter.
-
Save and Activate the Snippet.
b. Embedding the Form in a Page
-
Create a New Page:
- Go to WordPress Dashboard → Pages → Add New.
- Title it appropriately, e.g., "Website Preview".
-
Add the Shortcode:
- In the content area, insert the shortcode:
[preview_app_form]
-
Publish the Page.
2. Back-End Development
a. Redirecting Preview URLs
We need to handle URLs like hosts.dev/g89gjd and redirect them to givenomainacom.hosts.dev. This involves intercepting WordPress's request handling and performing the redirect based on the unique code.
Code Snippet for Handling Redirects
- Add the Following Code to the Same Snippet or a New Snippet in Code Snippets:
// Handle redirection for preview URLs
function preview_app_handle_redirects() {
global $wp;
$requested_slug = $wp->request;
if ( empty($requested_slug) ) {
return;
}
// Query for a preview post with the requested slug
$preview_posts = get_posts( array(
'post_type' => 'preview',
'title' => $requested_slug,
'numberposts' => 1,
));
if ( $preview_posts ) {
$preview = $preview_posts[0];
$domain = get_post_meta($preview->ID, 'domain', true);
$ip = get_post_meta($preview->ID, 'ip', true);
if ( $domain ) {
// Construct the wildcard subdomain URL
$redirect_url = 'https://' . preg_replace('/^www\./', '', $domain) . '.' . parse_url(home_url(), PHP_URL_HOST);
wp_redirect( $redirect_url, 302 );
exit;
}
}
}
add_action( 'template_redirect', 'preview_app_handle_redirects' );
-
Explanation of the Code:
-
Save and Activate the Snippet.
b. Notes on the Redirect Mechanism
-
Wildcards Configuration:
- Ensure that your Nginx and Cloudflare configurations correctly handle wildcard subdomains (
*.hosts.dev) to point to your server.
-
Security:
- The code ensures that only valid preview mappings are followed.
- Further security measures can be implemented as needed, such as limiting the number of redirects or adding expiration times.
3. Database Management with Custom Post Types
Using a custom post type (preview) is an efficient way to store and manage the mappings between unique codes and their respective domains and IPs.
a. Registering the Custom Post Type
The earlier snippet already includes the registration of the preview custom post type. Here's a quick recap:
// Register custom post type 'preview'
function register_preview_post_type() {
$labels = array(
'name' => 'Previews',
'singular_name' => 'Preview',
'menu_name' => 'Previews',
'name_admin_bar' => 'Preview',
'add_new' => 'Add New',
'add_new_item' => 'Add New Preview',
'new_item' => 'New Preview',
'edit_item' => 'Edit Preview',
'view_item' => 'View Preview',
'all_items' => 'All Previews',
'search_items' => 'Search Previews',
'not_found' => 'No previews found.',
'not_found_in_trash' => 'No previews found in Trash.',
);
$args = array(
'labels' => $labels,
'public' => false,
'publicly_queryable' => true,
'show_ui' => false,
'show_in_menu' => false,
'query_var' => true,
'rewrite' => array( 'slug' => '', 'with_front' => false ), // Root-level
'capability_type' => 'post',
'has_archive' => false,
'hierarchical' => false,
'supports' => array( 'title' ),
);
register_post_type('preview', $args);
}
add_action('init', 'register_preview_post_type');
b. Data Storage
Each preview post stores:
- Title: The unique code (e.g.,
g89gjd).
- Meta Fields:
domain: The domain entered by the client.
ip: The IP address entered by the client.
This structure allows efficient querying and management of the preview mappings.
4. Security Considerations
Ensuring the security of your application is paramount. Here's how the provided code addresses common security concerns:
a. Input Validation and Sanitization
-
Sanitization:
sanitize_text_field is used to sanitize the domain and ip inputs, stripping out any unwanted characters.
-
Validation:
- The domain is validated using a regular expression to ensure it follows a standard domain format.
- The IP address is validated using PHP's
filter_var with the FILTER_VALIDATE_IP filter.
b. Unique Code Generation
- The
generate_unique_code function ensures that each generated code is unique by checking existing entries. If a collision occurs, it recursively generates a new code.
c. Data Handling
- Handled in Non-Public Post Types:
- The
preview post type is set to public => false, preventing it from appearing in site navigation and search results.
- Only the redirect mechanism accesses the
preview posts based on the unique code.
d. Redirect Security
- The redirect URL is constructed by combining the sanitized domain with the host, preventing open redirects.
- Note: If you allow users to input arbitrary domains, ensure that your wildcard subdomain setup securely handles these redirects to prevent misuse.
5. Final Steps and Testing
a. Finalizing Cloudflare and Nginx Configurations
Ensure that:
-
Cloudflare Wildcard DNS:
- A wildcard CNAME or A record (e.g.,
*.hosts.dev) is set to point to your server's IP or appropriate target.
-
Nginx Configuration:
-
Your Nginx server block is configured to handle wildcard subdomains. An example configuration:
server {
listen 80;
server_name *.hosts.dev hosts.dev;
root /var/www/hosts.dev/public_html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # Update PHP version as needed
}
# Other configurations...
}
- SSL Configuration: If you're using SSL, ensure that wildcard certificates are correctly set up.
b. Testing the Application
-
Access the Form:
- Navigate to the page where you embedded
[preview_app_form].
- Fill in the domain and IP address fields with valid data.
-
Generate Preview URL:
- Submit the form.
- You should receive a preview URL like
https://hosts.dev/g89gjd.
-
Test the Redirect:
- Access the preview URL.
- It should redirect you to
https://givenomainacom.hosts.dev.
-
Verify DNS and Server Response:
- Ensure that
givenomainacom.hosts.dev resolves correctly via DNS and is handled properly by your server.
6. Additional Enhancements
a. Expiration of Preview URLs
To prevent the database from growing indefinitely:
- Implement Expiration:
- Add a timestamp when creating a preview.
- Set up a scheduled task (cron job) to delete or deactivate previews after a certain period.
b. Rate Limiting
To prevent abuse:
- Limit Submissions:
- Implement rate limiting to restrict how many previews a single user can create within a specific time frame.
c. User Authentication
If only authorized users should create previews:
- Restrict Access:
- Require users to log in before accessing the preview form.
- Modify the shortcode to check user roles and permissions.
d. Enhanced Validation
- Domain Verification:
- Optionally verify that the provided domain is correctly pointed to your server to ensure the redirect works as intended.
e. Error Handling
- User Feedback:
- Enhance error messages to provide more context or steps to resolve issues if the redirect fails.
Conclusion
By following the steps outlined above, you've successfully created a website preview application on your WordPress site hosts.dev. This setup allows clients to generate unique preview URLs that redirect to their specified subdomains. Remember to regularly monitor and maintain your setup to ensure security, performance, and reliability.
Feel free to further customize and enhance the application based on your specific requirements.