<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Amar Dewri on Medium]]></title>
        <description><![CDATA[Stories by Amar Dewri on Medium]]></description>
        <link>https://medium.com/@amardewri?source=rss-c924752ff010------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5NDULWV2g0ce_oln.</url>
            <title>Stories by Amar Dewri on Medium</title>
            <link>https://medium.com/@amardewri?source=rss-c924752ff010------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 01:28:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amardewri/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Solving URL Rewriting Challenges for Static Next.js Sites (SSG) on AWS S3 and AWS CloudFront]]></title>
            <link>https://medium.com/@amardewri/solving-url-rewriting-challenges-for-static-next-js-sites-ssg-on-aws-s3-and-aws-cloudfront-55fec9fe04ed?source=rss-c924752ff010------2</link>
            <guid isPermaLink="false">https://medium.com/p/55fec9fe04ed</guid>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[static-site-generation]]></category>
            <category><![CDATA[cloudfront-functions]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Amar Dewri]]></dc:creator>
            <pubDate>Mon, 19 Aug 2024 15:31:49 GMT</pubDate>
            <atom:updated>2024-08-19T23:29:45.300Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*QOv9rzs3qsQAAjgtiXz5Fw.png" /><figcaption>NEXT JS SSG deployment workflow on AWS S3 with AWS CoudFront</figcaption></figure><h3>Introduction</h3><p>When deploying a static Next.js site to AWS S3 and serving it through CloudFront, developers often encounter an issue where direct access to nested routes (e.g., https://www.example.com/about) results in an &quot;Access Denied&quot; error. This blog post will guide you through understanding the problem and implementing a solution using CloudFront Functions.</p><h3>The Problem</h3><p>Static site generators like Next.js create HTML files for each route. For example, the /about route might generate an about.html file. When hosting on S3 and serving through CloudFront, accessing the root URL works fine, but direct access to nested routes fails because CloudFront is looking for a directory instead of an HTML file.</p><p>This issue arises because S3, when used as a static file host, expects a full file path like /about.html rather than just /about. When a user tries to access a URL like /about directly, CloudFront forwards the request to S3, which then looks for a directory named about/ instead of the about.html file. Since the directory doesn’t exist, S3 returns an &quot;Access Denied&quot; error.</p><pre>&lt;Error&gt;<br>  &lt;Code&gt;AccessDenied&lt;/Code&gt;<br>  &lt;Message&gt;Access Denied&lt;/Message&gt;<br>  &lt;RequestId&gt;46CXQEV3W0P&lt;/RequestId&gt;<br>  &lt;HostId&gt;mHK8Ag6loIvPKsA1/80WRLT+glo4QGR91ky9+p4VWe8fpkz2tzcKKQpls0w=&lt;/HostId&gt;<br>&lt;/Error&gt;</pre><p>Interestingly, when users navigate through the site using links, everything works perfectly because the links generated by Next.js include the correct file extension (e.g., /about.html). This can make the problem harder to diagnose because it only surfaces when users try to access the pages directly or refresh the page.</p><h3>The Solution: CloudFront Functions</h3><p>CloudFront Functions provide a lightweight, cost-effective way to manipulate requests at the CDN edge. We can use a CloudFront Function to rewrite incoming URLs, appending .html when necessary, ensuring that CloudFront requests the correct file from S3.</p><h3>Step 1: Create a CloudFront Function</h3><ol><li>Navigate to the CloudFront console and select “Functions.”</li><li>Click “Create function.”</li><li>Name your function (e.g., “URLRewrite”).</li><li>Choose the “cloudfront-js-2.0” runtime.</li></ol><h3>Step 2: Implement the Function</h3><p>When writing your CloudFront Function, it’s important to note that CloudFront Functions use ECMAScript 5.1, which is a much older version of JavaScript. This means that modern JavaScript features like ES6 modules, let, const, arrow functions, and template literals are not supported.</p><p>For example, if you attempt to use the following modern JavaScript syntax:</p><pre>// Incorrect (CommonJS style):<br>exports.handler = async (event) =&gt; {<br>  // function body<br>};<br><br>// Correct (ES module style):<br>export const handler = async (event) =&gt; {<br>  const request = event.Records[0].cf.request;<br>  const uri = request.uri;<br><br>// If the URI is &#39;/&#39;, serve index.html<br>  if (uri === &#39;/&#39;) {<br>      request.uri = &#39;/index.html&#39;;<br>  }<br>  // If URI doesn&#39;t end with .html and isn&#39;t a file (doesn&#39;t contain a dot), append .html<br>  else if (!uri.endsWith(&#39;.html&#39;) &amp;&amp; !uri.includes(&#39;.&#39;)) {<br>      request.uri = `${uri}.html`;<br>  }<br>  return request;<br>};</pre><p>You’ll encounter an error stating:</p><pre>The CloudFront function associated with the CloudFront distribution is invalid or could not run. SyntaxError: Token &quot;request&quot; not supported in this version in 2.</pre><p>This error occurs because CloudFront Functions are strictly limited to the ECMAScript 5.1 standard. Therefore, you must use var instead of let or const, traditional function declarations instead of arrow functions, and string concatenation with + instead of template literals.</p><p>Here’s the correct version that is compatible with ECMAScript 5.1:</p><pre>function handler(event) {<br>    var request = event.request;<br>    var uri = request.uri;<br><br>    // If the URI is &#39;/&#39;, serve index.html<br>    if (uri === &#39;/&#39;) {<br>        request.uri = &#39;/index.html&#39;;<br>    }<br>    // If URI doesn&#39;t end with .html and isn&#39;t a file (doesn&#39;t contain a dot), append .html<br>    else if (uri.slice(-5) !== &#39;.html&#39; &amp;&amp; uri.indexOf(&#39;.&#39;) === -1) {<br>        request.uri = uri + &#39;.html&#39;;<br>    }<br><br>    return request;<br>}</pre><h4>Code Breakdown:</h4><ul><li><strong>Root URL Handling</strong>: The function checks if the requested URI is /. If so, it rewrites the request to serve the index.html file.</li><li><strong>Appending </strong><strong>.html</strong>: For other URLs, the function checks if the URI doesn&#39;t already end in .html and doesn&#39;t contain a dot (.), which indicates that the URI isn&#39;t referencing a file with an extension. If both conditions are met, .html is appended to the URI.</li></ul><p>This approach ensures compatibility with the ECMAScript 5.1 standard while achieving the desired URL rewriting behavior.</p><h3>Why ECMAScript 5.1?</h3><p>CloudFront Functions are designed to be lightweight, with sub-millisecond execution times. To achieve this, they support only a subset of JavaScript (ECMAScript 5.1). This older standard has a smaller runtime, which contributes to the speed and efficiency of CloudFront Functions. While this means you can’t use the latest JavaScript features, the trade-off is worth it for the performance and cost-effectiveness in high-traffic scenarios.</p><h3>Step 3: Test and Publish</h3><p>Before publishing the function, use the built-in testing tools in the CloudFront console to verify that your function works as expected. Test various scenarios, including:</p><ul><li>Root URL (/)</li><li>Nested routes (e.g., /about)</li><li>URLs with query parameters or fragments (e.g., /about?ref=homepage, /about#team)</li></ul><p>Once you’re satisfied with the results, publish the function.</p><h3>Step 4: Associate with Your Distribution</h3><ol><li>Go to your CloudFront distribution.</li><li>Select the “Behaviors” tab.</li><li>Create/Edit the behavior that handles your S3 origin.</li><li>Scroll down to “Function associations.”</li><li>For “Viewer request,” select “CloudFront Functions” from the dropdown.</li><li>Choose your published function (e.g., “CFFunctionOriginRequestURLRewrite”) from the “Function ARN / Name” dropdown.</li><li>Click “Save changes.”</li></ol><p><strong>Important:</strong> Double-check that you’re editing the correct distribution, especially if you’re managing multiple CloudFront distributions. It’s easy to confuse them if they have similar configurations.</p><h3>Step 5: Verify the Association</h3><ol><li>After saving the behavior changes, return to the CloudFront Functions section.</li><li>Select your function.</li><li>In the “Associated distributions” table, confirm that your distribution is listed with the correct event type (Viewer Request).</li></ol><p>If you don’t see the association in either view, try the following:</p><ul><li>Refresh the browser page to ensure you’re seeing the most up-to-date information.</li><li>Wait a few minutes, as changes can sometimes take a moment to propagate through AWS systems.</li><li>If the issue persists, try removing the association and re-adding it.</li></ul><h3>Common Pitfalls to Avoid</h3><ol><li><strong>Caching Issues</strong>: After making changes, you might need to invalidate your CloudFront cache to see the effects immediately. You can do this from the CloudFront console.</li><li><strong>Function Versioning</strong>: Ensure you’re using the latest published version of your function. If you’ve made changes, make sure to publish a new version and update the association.</li></ol><h3>Why This Works</h3><p>By rewriting the URL at the edge, we ensure that CloudFront requests the correct HTML file from S3. This approach resolves the “Access Denied” error and allows direct access to all routes of your Next.js site.</p><h3>Benefits of Using CloudFront Functions</h3><ol><li><strong>Performance</strong>: CloudFront Functions execute with sub-millisecond startup times, ensuring minimal latency.</li><li><strong>Cost-effective</strong>: They’re significantly cheaper than Lambda@Edge, making them ideal for high-traffic sites.</li><li><strong>Simplicity</strong>: CloudFront Functions are easy to set up and manage without needing separate IAM roles or complex configurations.</li></ol><h3>Alternative Approaches</h3><p>While CloudFront Functions provide a simple and effective solution, there are other alternatives you might consider:</p><ul><li><strong>S3 Static Website Hosting</strong>: You can configure S3 to serve default documents (like index.html) for specific paths. However, this approach is less flexible and doesn’t work well with custom domains or HTTPS without additional setup.</li><li><strong>Lambda@Edge</strong>: This offers more power and flexibility, allowing complex logic to be executed at the edge. However, it’s more expensive and complex to manage compared to CloudFront Functions.</li></ul><h3>Conclusion</h3><p>This solution solves the URL rewriting challenge for static Next.js sites hosted on S3 and served through CloudFront. By leveraging CloudFront Functions, we achieve a performant, cost-effective, and maintainable solution that ensures all routes of your Next.js application are accessible.</p><p>Remember to test thoroughly after implementation, especially if your site has complex routing or uses dynamic routes. Additionally, keep in mind the handling of non-HTML assets to avoid any unexpected issues. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55fec9fe04ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Deploy local LLM using Ollama Server and Ollama Web UI on Amazon EC2]]></title>
            <link>https://medium.com/@amardewri/how-to-deploy-local-llm-using-ollama-server-and-ollama-web-ui-on-amazon-ec2-91ffee49d9cc?source=rss-c924752ff010------2</link>
            <guid isPermaLink="false">https://medium.com/p/91ffee49d9cc</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[gen-ai-for-business]]></category>
            <category><![CDATA[local-llm]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[ollama]]></category>
            <dc:creator><![CDATA[Amar Dewri]]></dc:creator>
            <pubDate>Thu, 08 Feb 2024 07:19:52 GMT</pubDate>
            <atom:updated>2024-02-08T08:11:35.085Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to a comprehensive guide on deploying Ollama Server and Ollama Web UI on an Amazon EC2 instance. This setup is ideal for leveraging <strong><em>open-sourced</em></strong> <strong>local Large Language Model (LLM)</strong> AI capabilities within the cloud, ensuring <strong>data privacy</strong>, <strong>customizability</strong>, <strong>regulatory compliance</strong>, and <strong>cost-effective </strong>AI solutions. In this guide, we’ll walk through the process step-by-step, providing detailed instructions and references to ensure a smooth setup.</p><p><strong>Note:</strong> I had to go through multiple links and documents while doing this setup and have tried to collate them into one single document here. I have added the related links as <strong>reference </strong>below respective section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*0OwIAFyY_JSc_GQVMsIbuw.jpeg" /><figcaption>A high level architecture of the setup on AWS</figcaption></figure><h4>LLM: The Evolution from Traditional Models</h4><p>The journey from traditional LLMs to <strong>llama.cpp</strong> marks a significant shift. Traditional models <strong>required high-end GPUs</strong> and <strong>extensive technical expertise</strong>, making them <strong>inaccessible to many</strong>.</p><p>llama.cpp, however, democratizes AI by optimizing for CPUs and <strong>simplifying implementation</strong>, broadening the scope for individual developers and smaller teams.</p><h4>Why Ollama?</h4><p>Ollama stands out for enabling <strong>local access</strong> to large language models like Llama 2 and Code Llama, ensuring data privacy and security. It supports GPU acceleration on both macOS and Linux and provides programming libraries in Python and JavaScript. Under the <strong>MIT License</strong>, Ollama offers an accessible and flexible Gen AI solution.</p><p><a href="https://github.com/ollama/ollama">Reference</a></p><h4>Step-by-Step Guide to Setting Up Ollama on EC2</h4><p><strong>Step 1: Initialize Your EC2 Instance</strong></p><p>The below configuration is for a <strong>GPU enabled EC2 instance</strong>, however it can be done on a CPU only instance as well. For CPU based instances we can skip the NVIDIA driver setup.</p><p>Configure an Amazon Linux 2 EC2 instance:</p><ul><li>Instance Type: g4dn.xlarge (~ $390 per month for the below configuration). <a href="https://calculator.aws/">Reference</a></li><li>vCPU: 4</li><li>RAM: 16GB</li><li>GPU: 1 (VRAM: 16GB)</li><li>EBS: 100GB (gp3)</li><li>OS: Amazon Linux 2</li><li>SSH Key: Required for PuTTY login</li></ul><p><strong>Step 2: Configure AWS CLI</strong></p><p>Install (Amazon Linux 2 comes pre-installed with AWS CLI) and configure the AWS CLI for <strong>your region</strong>. Use aws configure and omit the access key and secret access key if using an AWS Instance Role.</p><p><strong>Step 3: Create an Instance Role with S3 access</strong></p><p>Set up an <strong>instance role</strong> with AWS S3 access (preferably full access for initial testing) for downloading NVIDIA drivers. EC2 NVIDIA drivers are hosted on AWS S3 endpoints which we will use to download to our EC2 and install the drivers.</p><p><strong>Step 4: Verify S3 Access</strong></p><p>Ensure S3 access is working and we are able to list the S3 buckets in our account:</p><pre>aws s3 ls</pre><p><strong>Step 5: Install NVIDIA GRID Drivers</strong></p><p>g4dn EC2 instances require GRID drivers so we will install NVIDIA GRID drivers:</p><pre>sudo yum update -y<br>sudo yum install gcc make<br>sudo reboot<br>sudo yum install -y gcc kernel-devel-$(uname -r)<br>cd /home/ec2-user<br>aws s3 cp --recursive s3://ec2-linux-nvidia-drivers/latest/ .<br>chmod +x NVIDIA-Linux-x86_64*.run</pre><p>For Amazon Linux 2 with kernel version 5.10 (uname -a) run the below command:</p><p>I faced some issues when running the below command as ec2-user, so run the below commands as <strong>ROOT</strong> user as mentioned.</p><pre>mkdir /home/ec2-user/tmp<br>chmod -R 777 tmp<br>sudo su -<br>cd /home/ec2-user<br>export TMPDIR=/home/ec2-user/tmp<br>CC=/usr/bin/gcc10-cc ./NVIDIA-Linux-x86_64*.run --tmpdir=$TMPDIR</pre><p>This will launch the driver installation screen. Follow the instructions and chose the default options (there will be few warnings, press OK and proceed). Verify the drivers are installed and disable GSP on g4dn instance.</p><pre>nvidia-smi -q | head<br>sudo touch /etc/modprobe.d/nvidia.conf<br>echo &quot;options nvidia NVreg_EnableGpuFirmware=0&quot; | sudo tee --append /etc/modprobe.d/nvidia.conf<br>sudo reboot</pre><p><a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/install-nvidia-driver.html#nvidia-GRID-driver">Reference</a></p><p><strong>Step 6: Set Up Docker Engine</strong></p><p>Install Docker Engine on the Amazon Linux 2:</p><pre>sudo yum update -y<br>sudo yum install docker<br>sudo usermod -a -G docker ec2-user<br>sudo systemctl enable docker.service<br>sudo systemctl start docker.service<br>sudo systemctl status docker.service</pre><p>Log out and login to enable the group added and access the docker commands as non-root user.</p><p><a href="https://www.cyberciti.biz/faq/how-to-install-docker-on-amazon-linux-2/">Reference</a></p><p><strong>Step 7: Install NVIDIA Drivers for Docker</strong></p><p>Configure Docker with NVIDIA drivers:</p><pre>curl -s -L https://nvidia.github.io/libnvidia-container/stable/rpm/nvidia-container-toolkit.repo | \<br>  sudo tee /etc/yum.repos.d/nvidia-container-toolkit.repo<br><br>sudo yum install -y nvidia-container-toolkit</pre><p><a href="https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html#installation">Reference</a></p><p><strong>Step 8: Configure Docker for NVIDIA Drivers</strong></p><p>Enable NVIDIA drivers in Docker:</p><pre>sudo nvidia-ctk runtime configure --runtime=docker<br>sudo systemctl restart docker</pre><p><a href="https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html#configuring-docker">Reference</a></p><p><strong>Step 9: Install Ollama Server Docker Container</strong></p><p>Deploy the Ollama server with GPU option to leverage the EC2 GPU:</p><pre>docker run -d --gpus=all -v ollama:/root/.ollama -p 11434:11434 --name ollama --restart always ollama/ollama</pre><p>Verify the ollama server is accessible at <a href="http://hostname:11434.">http://hostname:11434</a></p><p>Replace hostname with the instance IP or hostname or localhost or 127.0.0.1</p><p><a href="https://ollama.ai/blog/ollama-is-now-available-as-an-official-docker-image">Reference</a></p><p><strong>Step 10: Download Required LLM Models of your choice</strong></p><p>Pull required models from the Ollama library:</p><p>Refer to the <a href="https://ollama.ai/library/codellama/tags">tags</a> against each model in the <a href="https://ollama.ai/library">ollama library</a> and test with the smaller models (7b) first. Larger models (13b, 33b etc.) require more GPU and can impact performance. Below models, I found to be good enough to start with; they are between 3–5 GB in size.</p><pre>docker exec -it ollama ollama pull deepseek-llm <br>docker exec -it ollama ollama pull llama2 <br>docker exec -it ollama ollama pull deepseek-coder:6.7b <br>docker exec -it ollama ollama pull codellama:7b</pre><p><a href="https://ollama.ai/library">Reference</a></p><p><strong>Step 11: Install Ollama Web UI Container</strong></p><p>To access the local LLM with a Chat-GPT like interface set up the ollama web-ui. Other options can be explored <a href="https://github.com/ollama/ollama?tab=readme-ov-file#web--desktop">here</a>.</p><pre>docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v ollama-webui:/app/backend/data --name ollama-webui --restart always ghcr.io/ollama-webui/ollama-webui:main</pre><p>Optionally we can access the LLM using CLI command as well:</p><pre>docker exec -it ollama ollama run llama2</pre><p><a href="https://github.com/ollama-webui/ollama-webui">Reference</a></p><p><strong>Step 12: Access the Ollama Web UI</strong></p><p>Access the Web UI at <a href="http://hostname:3000/">http://hostname:3000</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*wwNWfU4xr_iphg8SYwYvGw.png" /><figcaption>Chat-GPT like interface with Ollama Web-UI using Codellama:7b</figcaption></figure><h4>Conclusion</h4><p>By following these steps, we can successfully deploy Ollama Server and Ollama Web UI on Amazon EC2, unlocking powerful local AI capabilities. This guide provides a roadmap for developers and IT professionals to integrate advanced AI models into their cloud infrastructure while maintaining data privacy and cost efficiency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91ffee49d9cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>